[SCSI] iscsi_tcp: remove DMA alignment restriction
[safe/jmp/linux-2.6] / drivers / scsi / iscsi_tcp.c
1 /*
2  * iSCSI Initiator over TCP/IP Data-Path
3  *
4  * Copyright (C) 2004 Dmitry Yusupov
5  * Copyright (C) 2004 Alex Aizman
6  * Copyright (C) 2005 - 2006 Mike Christie
7  * Copyright (C) 2006 Red Hat, Inc.  All rights reserved.
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
12  * by 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, but
16  * WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18  * General Public License for more details.
19  *
20  * See the file COPYING included with this distribution for more details.
21  *
22  * Credits:
23  *      Christoph Hellwig
24  *      FUJITA Tomonori
25  *      Arne Redlich
26  *      Zhenyu Wang
27  */
28
29 #include <linux/types.h>
30 #include <linux/list.h>
31 #include <linux/inet.h>
32 #include <linux/blkdev.h>
33 #include <linux/crypto.h>
34 #include <linux/delay.h>
35 #include <linux/kfifo.h>
36 #include <linux/scatterlist.h>
37 #include <net/tcp.h>
38 #include <scsi/scsi_cmnd.h>
39 #include <scsi/scsi_device.h>
40 #include <scsi/scsi_host.h>
41 #include <scsi/scsi.h>
42 #include <scsi/scsi_transport_iscsi.h>
43
44 #include "iscsi_tcp.h"
45
46 MODULE_AUTHOR("Dmitry Yusupov <dmitry_yus@yahoo.com>, "
47               "Alex Aizman <itn780@yahoo.com>");
48 MODULE_DESCRIPTION("iSCSI/TCP data-path");
49 MODULE_LICENSE("GPL");
50 /* #define DEBUG_TCP */
51 #define DEBUG_ASSERT
52
53 #ifdef DEBUG_TCP
54 #define debug_tcp(fmt...) printk(KERN_INFO "tcp: " fmt)
55 #else
56 #define debug_tcp(fmt...)
57 #endif
58
59 #ifndef DEBUG_ASSERT
60 #ifdef BUG_ON
61 #undef BUG_ON
62 #endif
63 #define BUG_ON(expr)
64 #endif
65
66 static unsigned int iscsi_max_lun = 512;
67 module_param_named(max_lun, iscsi_max_lun, uint, S_IRUGO);
68
69 static inline void
70 iscsi_buf_init_iov(struct iscsi_buf *ibuf, char *vbuf, int size)
71 {
72         ibuf->sg.page = virt_to_page(vbuf);
73         ibuf->sg.offset = offset_in_page(vbuf);
74         ibuf->sg.length = size;
75         ibuf->sent = 0;
76         ibuf->use_sendmsg = 1;
77 }
78
79 static inline void
80 iscsi_buf_init_sg(struct iscsi_buf *ibuf, struct scatterlist *sg)
81 {
82         ibuf->sg.page = sg->page;
83         ibuf->sg.offset = sg->offset;
84         ibuf->sg.length = sg->length;
85         /*
86          * Fastpath: sg element fits into single page
87          */
88         if (sg->length + sg->offset <= PAGE_SIZE && !PageSlab(sg->page))
89                 ibuf->use_sendmsg = 0;
90         else
91                 ibuf->use_sendmsg = 1;
92         ibuf->sent = 0;
93 }
94
95 static inline int
96 iscsi_buf_left(struct iscsi_buf *ibuf)
97 {
98         int rc;
99
100         rc = ibuf->sg.length - ibuf->sent;
101         BUG_ON(rc < 0);
102         return rc;
103 }
104
105 static inline void
106 iscsi_hdr_digest(struct iscsi_conn *conn, struct iscsi_buf *buf,
107                  u8* crc)
108 {
109         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
110
111         crypto_hash_digest(&tcp_conn->tx_hash, &buf->sg, buf->sg.length, crc);
112         buf->sg.length += sizeof(u32);
113 }
114
115 static inline int
116 iscsi_hdr_extract(struct iscsi_tcp_conn *tcp_conn)
117 {
118         struct sk_buff *skb = tcp_conn->in.skb;
119
120         tcp_conn->in.zero_copy_hdr = 0;
121
122         if (tcp_conn->in.copy >= tcp_conn->hdr_size &&
123             tcp_conn->in_progress == IN_PROGRESS_WAIT_HEADER) {
124                 /*
125                  * Zero-copy PDU Header: using connection context
126                  * to store header pointer.
127                  */
128                 if (skb_shinfo(skb)->frag_list == NULL &&
129                     !skb_shinfo(skb)->nr_frags) {
130                         tcp_conn->in.hdr = (struct iscsi_hdr *)
131                                 ((char*)skb->data + tcp_conn->in.offset);
132                         tcp_conn->in.zero_copy_hdr = 1;
133                 } else {
134                         /* ignoring return code since we checked
135                          * in.copy before */
136                         skb_copy_bits(skb, tcp_conn->in.offset,
137                                 &tcp_conn->hdr, tcp_conn->hdr_size);
138                         tcp_conn->in.hdr = &tcp_conn->hdr;
139                 }
140                 tcp_conn->in.offset += tcp_conn->hdr_size;
141                 tcp_conn->in.copy -= tcp_conn->hdr_size;
142         } else {
143                 int hdr_remains;
144                 int copylen;
145
146                 /*
147                  * PDU header scattered across SKB's,
148                  * copying it... This'll happen quite rarely.
149                  */
150
151                 if (tcp_conn->in_progress == IN_PROGRESS_WAIT_HEADER)
152                         tcp_conn->in.hdr_offset = 0;
153
154                 hdr_remains = tcp_conn->hdr_size - tcp_conn->in.hdr_offset;
155                 BUG_ON(hdr_remains <= 0);
156
157                 copylen = min(tcp_conn->in.copy, hdr_remains);
158                 skb_copy_bits(skb, tcp_conn->in.offset,
159                         (char*)&tcp_conn->hdr + tcp_conn->in.hdr_offset,
160                         copylen);
161
162                 debug_tcp("PDU gather offset %d bytes %d in.offset %d "
163                        "in.copy %d\n", tcp_conn->in.hdr_offset, copylen,
164                        tcp_conn->in.offset, tcp_conn->in.copy);
165
166                 tcp_conn->in.offset += copylen;
167                 tcp_conn->in.copy -= copylen;
168                 if (copylen < hdr_remains)  {
169                         tcp_conn->in_progress = IN_PROGRESS_HEADER_GATHER;
170                         tcp_conn->in.hdr_offset += copylen;
171                         return -EAGAIN;
172                 }
173                 tcp_conn->in.hdr = &tcp_conn->hdr;
174                 tcp_conn->discontiguous_hdr_cnt++;
175                 tcp_conn->in_progress = IN_PROGRESS_WAIT_HEADER;
176         }
177
178         return 0;
179 }
180
181 /*
182  * must be called with session lock
183  */
184 static void
185 iscsi_tcp_cleanup_ctask(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
186 {
187         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
188         struct iscsi_r2t_info *r2t;
189         struct scsi_cmnd *sc;
190
191         /* flush ctask's r2t queues */
192         while (__kfifo_get(tcp_ctask->r2tqueue, (void*)&r2t, sizeof(void*))) {
193                 __kfifo_put(tcp_ctask->r2tpool.queue, (void*)&r2t,
194                             sizeof(void*));
195                 debug_scsi("iscsi_tcp_cleanup_ctask pending r2t dropped\n");
196         }
197
198         sc = ctask->sc;
199         if (unlikely(!sc))
200                 return;
201
202         tcp_ctask->xmstate = XMSTATE_IDLE;
203         tcp_ctask->r2t = NULL;
204 }
205
206 /**
207  * iscsi_data_rsp - SCSI Data-In Response processing
208  * @conn: iscsi connection
209  * @ctask: scsi command task
210  **/
211 static int
212 iscsi_data_rsp(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
213 {
214         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
215         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
216         struct iscsi_data_rsp *rhdr = (struct iscsi_data_rsp *)tcp_conn->in.hdr;
217         struct iscsi_session *session = conn->session;
218         struct scsi_cmnd *sc = ctask->sc;
219         int datasn = be32_to_cpu(rhdr->datasn);
220
221         iscsi_update_cmdsn(session, (struct iscsi_nopin*)rhdr);
222         /*
223          * setup Data-In byte counter (gets decremented..)
224          */
225         ctask->data_count = tcp_conn->in.datalen;
226
227         if (tcp_conn->in.datalen == 0)
228                 return 0;
229
230         if (tcp_ctask->exp_datasn != datasn) {
231                 debug_tcp("%s: ctask->exp_datasn(%d) != rhdr->datasn(%d)\n",
232                           __FUNCTION__, tcp_ctask->exp_datasn, datasn);
233                 return ISCSI_ERR_DATASN;
234         }
235
236         tcp_ctask->exp_datasn++;
237
238         tcp_ctask->data_offset = be32_to_cpu(rhdr->offset);
239         if (tcp_ctask->data_offset + tcp_conn->in.datalen > sc->request_bufflen) {
240                 debug_tcp("%s: data_offset(%d) + data_len(%d) > total_length_in(%d)\n",
241                           __FUNCTION__, tcp_ctask->data_offset,
242                           tcp_conn->in.datalen, sc->request_bufflen);
243                 return ISCSI_ERR_DATA_OFFSET;
244         }
245
246         if (rhdr->flags & ISCSI_FLAG_DATA_STATUS) {
247                 conn->exp_statsn = be32_to_cpu(rhdr->statsn) + 1;
248                 if (rhdr->flags & ISCSI_FLAG_DATA_UNDERFLOW) {
249                         int res_count = be32_to_cpu(rhdr->residual_count);
250
251                         if (res_count > 0 &&
252                             res_count <= sc->request_bufflen) {
253                                 sc->resid = res_count;
254                                 sc->result = (DID_OK << 16) | rhdr->cmd_status;
255                         } else
256                                 sc->result = (DID_BAD_TARGET << 16) |
257                                         rhdr->cmd_status;
258                 } else if (rhdr->flags & ISCSI_FLAG_DATA_OVERFLOW) {
259                         sc->resid = be32_to_cpu(rhdr->residual_count);
260                         sc->result = (DID_OK << 16) | rhdr->cmd_status;
261                 } else
262                         sc->result = (DID_OK << 16) | rhdr->cmd_status;
263         }
264
265         conn->datain_pdus_cnt++;
266         return 0;
267 }
268
269 /**
270  * iscsi_solicit_data_init - initialize first Data-Out
271  * @conn: iscsi connection
272  * @ctask: scsi command task
273  * @r2t: R2T info
274  *
275  * Notes:
276  *      Initialize first Data-Out within this R2T sequence and finds
277  *      proper data_offset within this SCSI command.
278  *
279  *      This function is called with connection lock taken.
280  **/
281 static void
282 iscsi_solicit_data_init(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask,
283                         struct iscsi_r2t_info *r2t)
284 {
285         struct iscsi_data *hdr;
286         struct scsi_cmnd *sc = ctask->sc;
287
288         hdr = &r2t->dtask.hdr;
289         memset(hdr, 0, sizeof(struct iscsi_data));
290         hdr->ttt = r2t->ttt;
291         hdr->datasn = cpu_to_be32(r2t->solicit_datasn);
292         r2t->solicit_datasn++;
293         hdr->opcode = ISCSI_OP_SCSI_DATA_OUT;
294         memcpy(hdr->lun, ctask->hdr->lun, sizeof(hdr->lun));
295         hdr->itt = ctask->hdr->itt;
296         hdr->exp_statsn = r2t->exp_statsn;
297         hdr->offset = cpu_to_be32(r2t->data_offset);
298         if (r2t->data_length > conn->max_xmit_dlength) {
299                 hton24(hdr->dlength, conn->max_xmit_dlength);
300                 r2t->data_count = conn->max_xmit_dlength;
301                 hdr->flags = 0;
302         } else {
303                 hton24(hdr->dlength, r2t->data_length);
304                 r2t->data_count = r2t->data_length;
305                 hdr->flags = ISCSI_FLAG_CMD_FINAL;
306         }
307         conn->dataout_pdus_cnt++;
308
309         r2t->sent = 0;
310
311         iscsi_buf_init_iov(&r2t->headbuf, (char*)hdr,
312                            sizeof(struct iscsi_hdr));
313
314         if (sc->use_sg) {
315                 int i, sg_count = 0;
316                 struct scatterlist *sg = sc->request_buffer;
317
318                 r2t->sg = NULL;
319                 for (i = 0; i < sc->use_sg; i++, sg += 1) {
320                         /* FIXME: prefetch ? */
321                         if (sg_count + sg->length > r2t->data_offset) {
322                                 int page_offset;
323
324                                 /* sg page found! */
325
326                                 /* offset within this page */
327                                 page_offset = r2t->data_offset - sg_count;
328
329                                 /* fill in this buffer */
330                                 iscsi_buf_init_sg(&r2t->sendbuf, sg);
331                                 r2t->sendbuf.sg.offset += page_offset;
332                                 r2t->sendbuf.sg.length -= page_offset;
333
334                                 /* xmit logic will continue with next one */
335                                 r2t->sg = sg + 1;
336                                 break;
337                         }
338                         sg_count += sg->length;
339                 }
340                 BUG_ON(r2t->sg == NULL);
341         } else {
342                 iscsi_buf_init_iov(&r2t->sendbuf,
343                             (char*)sc->request_buffer + r2t->data_offset,
344                             r2t->data_count);
345                 r2t->sg = NULL;
346         }
347 }
348
349 /**
350  * iscsi_r2t_rsp - iSCSI R2T Response processing
351  * @conn: iscsi connection
352  * @ctask: scsi command task
353  **/
354 static int
355 iscsi_r2t_rsp(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
356 {
357         struct iscsi_r2t_info *r2t;
358         struct iscsi_session *session = conn->session;
359         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
360         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
361         struct iscsi_r2t_rsp *rhdr = (struct iscsi_r2t_rsp *)tcp_conn->in.hdr;
362         int r2tsn = be32_to_cpu(rhdr->r2tsn);
363         int rc;
364
365         if (tcp_conn->in.datalen) {
366                 printk(KERN_ERR "iscsi_tcp: invalid R2t with datalen %d\n",
367                        tcp_conn->in.datalen);
368                 return ISCSI_ERR_DATALEN;
369         }
370
371         if (tcp_ctask->exp_datasn != r2tsn){
372                 debug_tcp("%s: ctask->exp_datasn(%d) != rhdr->r2tsn(%d)\n",
373                           __FUNCTION__, tcp_ctask->exp_datasn, r2tsn);
374                 return ISCSI_ERR_R2TSN;
375         }
376
377         /* fill-in new R2T associated with the task */
378         spin_lock(&session->lock);
379         iscsi_update_cmdsn(session, (struct iscsi_nopin*)rhdr);
380
381         if (!ctask->sc || ctask->mtask ||
382              session->state != ISCSI_STATE_LOGGED_IN) {
383                 printk(KERN_INFO "iscsi_tcp: dropping R2T itt %d in "
384                        "recovery...\n", ctask->itt);
385                 spin_unlock(&session->lock);
386                 return 0;
387         }
388
389         rc = __kfifo_get(tcp_ctask->r2tpool.queue, (void*)&r2t, sizeof(void*));
390         BUG_ON(!rc);
391
392         r2t->exp_statsn = rhdr->statsn;
393         r2t->data_length = be32_to_cpu(rhdr->data_length);
394         if (r2t->data_length == 0) {
395                 printk(KERN_ERR "iscsi_tcp: invalid R2T with zero data len\n");
396                 spin_unlock(&session->lock);
397                 return ISCSI_ERR_DATALEN;
398         }
399
400         if (r2t->data_length > session->max_burst)
401                 debug_scsi("invalid R2T with data len %u and max burst %u."
402                            "Attempting to execute request.\n",
403                             r2t->data_length, session->max_burst);
404
405         r2t->data_offset = be32_to_cpu(rhdr->data_offset);
406         if (r2t->data_offset + r2t->data_length > ctask->sc->request_bufflen) {
407                 spin_unlock(&session->lock);
408                 printk(KERN_ERR "iscsi_tcp: invalid R2T with data len %u at "
409                        "offset %u and total length %d\n", r2t->data_length,
410                        r2t->data_offset, ctask->sc->request_bufflen);
411                 return ISCSI_ERR_DATALEN;
412         }
413
414         r2t->ttt = rhdr->ttt; /* no flip */
415         r2t->solicit_datasn = 0;
416
417         iscsi_solicit_data_init(conn, ctask, r2t);
418
419         tcp_ctask->exp_datasn = r2tsn + 1;
420         __kfifo_put(tcp_ctask->r2tqueue, (void*)&r2t, sizeof(void*));
421         tcp_ctask->xmstate |= XMSTATE_SOL_HDR_INIT;
422         list_move_tail(&ctask->running, &conn->xmitqueue);
423
424         scsi_queue_work(session->host, &conn->xmitwork);
425         conn->r2t_pdus_cnt++;
426         spin_unlock(&session->lock);
427
428         return 0;
429 }
430
431 static int
432 iscsi_tcp_hdr_recv(struct iscsi_conn *conn)
433 {
434         int rc = 0, opcode, ahslen;
435         struct iscsi_hdr *hdr;
436         struct iscsi_session *session = conn->session;
437         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
438         uint32_t cdgst, rdgst = 0, itt;
439
440         hdr = tcp_conn->in.hdr;
441
442         /* verify PDU length */
443         tcp_conn->in.datalen = ntoh24(hdr->dlength);
444         if (tcp_conn->in.datalen > conn->max_recv_dlength) {
445                 printk(KERN_ERR "iscsi_tcp: datalen %d > %d\n",
446                        tcp_conn->in.datalen, conn->max_recv_dlength);
447                 return ISCSI_ERR_DATALEN;
448         }
449         tcp_conn->data_copied = 0;
450
451         /* read AHS */
452         ahslen = hdr->hlength << 2;
453         tcp_conn->in.offset += ahslen;
454         tcp_conn->in.copy -= ahslen;
455         if (tcp_conn->in.copy < 0) {
456                 printk(KERN_ERR "iscsi_tcp: can't handle AHS with length "
457                        "%d bytes\n", ahslen);
458                 return ISCSI_ERR_AHSLEN;
459         }
460
461         /* calculate read padding */
462         tcp_conn->in.padding = tcp_conn->in.datalen & (ISCSI_PAD_LEN-1);
463         if (tcp_conn->in.padding) {
464                 tcp_conn->in.padding = ISCSI_PAD_LEN - tcp_conn->in.padding;
465                 debug_scsi("read padding %d bytes\n", tcp_conn->in.padding);
466         }
467
468         if (conn->hdrdgst_en) {
469                 struct scatterlist sg;
470
471                 sg_init_one(&sg, (u8 *)hdr,
472                             sizeof(struct iscsi_hdr) + ahslen);
473                 crypto_hash_digest(&tcp_conn->rx_hash, &sg, sg.length,
474                                    (u8 *)&cdgst);
475                 rdgst = *(uint32_t*)((char*)hdr + sizeof(struct iscsi_hdr) +
476                                      ahslen);
477                 if (cdgst != rdgst) {
478                         printk(KERN_ERR "iscsi_tcp: hdrdgst error "
479                                "recv 0x%x calc 0x%x\n", rdgst, cdgst);
480                         return ISCSI_ERR_HDR_DGST;
481                 }
482         }
483
484         opcode = hdr->opcode & ISCSI_OPCODE_MASK;
485         /* verify itt (itt encoding: age+cid+itt) */
486         rc = iscsi_verify_itt(conn, hdr, &itt);
487         if (rc == ISCSI_ERR_NO_SCSI_CMD) {
488                 tcp_conn->in.datalen = 0; /* force drop */
489                 return 0;
490         } else if (rc)
491                 return rc;
492
493         debug_tcp("opcode 0x%x offset %d copy %d ahslen %d datalen %d\n",
494                   opcode, tcp_conn->in.offset, tcp_conn->in.copy,
495                   ahslen, tcp_conn->in.datalen);
496
497         switch(opcode) {
498         case ISCSI_OP_SCSI_DATA_IN:
499                 tcp_conn->in.ctask = session->cmds[itt];
500                 rc = iscsi_data_rsp(conn, tcp_conn->in.ctask);
501                 if (rc)
502                         return rc;
503                 /* fall through */
504         case ISCSI_OP_SCSI_CMD_RSP:
505                 tcp_conn->in.ctask = session->cmds[itt];
506                 if (tcp_conn->in.datalen)
507                         goto copy_hdr;
508
509                 spin_lock(&session->lock);
510                 rc = __iscsi_complete_pdu(conn, hdr, NULL, 0);
511                 spin_unlock(&session->lock);
512                 break;
513         case ISCSI_OP_R2T:
514                 tcp_conn->in.ctask = session->cmds[itt];
515                 if (ahslen)
516                         rc = ISCSI_ERR_AHSLEN;
517                 else if (tcp_conn->in.ctask->sc->sc_data_direction ==
518                                                                 DMA_TO_DEVICE)
519                         rc = iscsi_r2t_rsp(conn, tcp_conn->in.ctask);
520                 else
521                         rc = ISCSI_ERR_PROTO;
522                 break;
523         case ISCSI_OP_LOGIN_RSP:
524         case ISCSI_OP_TEXT_RSP:
525         case ISCSI_OP_REJECT:
526         case ISCSI_OP_ASYNC_EVENT:
527                 /*
528                  * It is possible that we could get a PDU with a buffer larger
529                  * than 8K, but there are no targets that currently do this.
530                  * For now we fail until we find a vendor that needs it
531                  */
532                 if (ISCSI_DEF_MAX_RECV_SEG_LEN <
533                     tcp_conn->in.datalen) {
534                         printk(KERN_ERR "iscsi_tcp: received buffer of len %u "
535                               "but conn buffer is only %u (opcode %0x)\n",
536                               tcp_conn->in.datalen,
537                               ISCSI_DEF_MAX_RECV_SEG_LEN, opcode);
538                         rc = ISCSI_ERR_PROTO;
539                         break;
540                 }
541
542                 if (tcp_conn->in.datalen)
543                         goto copy_hdr;
544         /* fall through */
545         case ISCSI_OP_LOGOUT_RSP:
546         case ISCSI_OP_NOOP_IN:
547         case ISCSI_OP_SCSI_TMFUNC_RSP:
548                 rc = iscsi_complete_pdu(conn, hdr, NULL, 0);
549                 break;
550         default:
551                 rc = ISCSI_ERR_BAD_OPCODE;
552                 break;
553         }
554
555         return rc;
556
557 copy_hdr:
558         /*
559          * if we did zero copy for the header but we will need multiple
560          * skbs to complete the command then we have to copy the header
561          * for later use
562          */
563         if (tcp_conn->in.zero_copy_hdr && tcp_conn->in.copy <=
564            (tcp_conn->in.datalen + tcp_conn->in.padding +
565             (conn->datadgst_en ? 4 : 0))) {
566                 debug_tcp("Copying header for later use. in.copy %d in.datalen"
567                           " %d\n", tcp_conn->in.copy, tcp_conn->in.datalen);
568                 memcpy(&tcp_conn->hdr, tcp_conn->in.hdr,
569                        sizeof(struct iscsi_hdr));
570                 tcp_conn->in.hdr = &tcp_conn->hdr;
571                 tcp_conn->in.zero_copy_hdr = 0;
572         }
573         return 0;
574 }
575
576 /**
577  * iscsi_ctask_copy - copy skb bits to the destanation cmd task
578  * @conn: iscsi tcp connection
579  * @ctask: scsi command task
580  * @buf: buffer to copy to
581  * @buf_size: size of buffer
582  * @offset: offset within the buffer
583  *
584  * Notes:
585  *      The function calls skb_copy_bits() and updates per-connection and
586  *      per-cmd byte counters.
587  *
588  *      Read counters (in bytes):
589  *
590  *      conn->in.offset         offset within in progress SKB
591  *      conn->in.copy           left to copy from in progress SKB
592  *                              including padding
593  *      conn->in.copied         copied already from in progress SKB
594  *      conn->data_copied       copied already from in progress buffer
595  *      ctask->sent             total bytes sent up to the MidLayer
596  *      ctask->data_count       left to copy from in progress Data-In
597  *      buf_left                left to copy from in progress buffer
598  **/
599 static inline int
600 iscsi_ctask_copy(struct iscsi_tcp_conn *tcp_conn, struct iscsi_cmd_task *ctask,
601                 void *buf, int buf_size, int offset)
602 {
603         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
604         int buf_left = buf_size - (tcp_conn->data_copied + offset);
605         unsigned size = min(tcp_conn->in.copy, buf_left);
606         int rc;
607
608         size = min(size, ctask->data_count);
609
610         debug_tcp("ctask_copy %d bytes at offset %d copied %d\n",
611                size, tcp_conn->in.offset, tcp_conn->in.copied);
612
613         BUG_ON(size <= 0);
614         BUG_ON(tcp_ctask->sent + size > ctask->sc->request_bufflen);
615
616         rc = skb_copy_bits(tcp_conn->in.skb, tcp_conn->in.offset,
617                            (char*)buf + (offset + tcp_conn->data_copied), size);
618         /* must fit into skb->len */
619         BUG_ON(rc);
620
621         tcp_conn->in.offset += size;
622         tcp_conn->in.copy -= size;
623         tcp_conn->in.copied += size;
624         tcp_conn->data_copied += size;
625         tcp_ctask->sent += size;
626         ctask->data_count -= size;
627
628         BUG_ON(tcp_conn->in.copy < 0);
629         BUG_ON(ctask->data_count < 0);
630
631         if (buf_size != (tcp_conn->data_copied + offset)) {
632                 if (!ctask->data_count) {
633                         BUG_ON(buf_size - tcp_conn->data_copied < 0);
634                         /* done with this PDU */
635                         return buf_size - tcp_conn->data_copied;
636                 }
637                 return -EAGAIN;
638         }
639
640         /* done with this buffer or with both - PDU and buffer */
641         tcp_conn->data_copied = 0;
642         return 0;
643 }
644
645 /**
646  * iscsi_tcp_copy - copy skb bits to the destanation buffer
647  * @conn: iscsi tcp connection
648  *
649  * Notes:
650  *      The function calls skb_copy_bits() and updates per-connection
651  *      byte counters.
652  **/
653 static inline int
654 iscsi_tcp_copy(struct iscsi_conn *conn, int buf_size)
655 {
656         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
657         int buf_left = buf_size - tcp_conn->data_copied;
658         int size = min(tcp_conn->in.copy, buf_left);
659         int rc;
660
661         debug_tcp("tcp_copy %d bytes at offset %d copied %d\n",
662                size, tcp_conn->in.offset, tcp_conn->data_copied);
663         BUG_ON(size <= 0);
664
665         rc = skb_copy_bits(tcp_conn->in.skb, tcp_conn->in.offset,
666                            (char*)conn->data + tcp_conn->data_copied, size);
667         BUG_ON(rc);
668
669         tcp_conn->in.offset += size;
670         tcp_conn->in.copy -= size;
671         tcp_conn->in.copied += size;
672         tcp_conn->data_copied += size;
673
674         if (buf_size != tcp_conn->data_copied)
675                 return -EAGAIN;
676
677         return 0;
678 }
679
680 static inline void
681 partial_sg_digest_update(struct hash_desc *desc, struct scatterlist *sg,
682                          int offset, int length)
683 {
684         struct scatterlist temp;
685
686         memcpy(&temp, sg, sizeof(struct scatterlist));
687         temp.offset = offset;
688         temp.length = length;
689         crypto_hash_update(desc, &temp, length);
690 }
691
692 static void
693 iscsi_recv_digest_update(struct iscsi_tcp_conn *tcp_conn, char* buf, int len)
694 {
695         struct scatterlist tmp;
696
697         sg_init_one(&tmp, buf, len);
698         crypto_hash_update(&tcp_conn->rx_hash, &tmp, len);
699 }
700
701 static int iscsi_scsi_data_in(struct iscsi_conn *conn)
702 {
703         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
704         struct iscsi_cmd_task *ctask = tcp_conn->in.ctask;
705         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
706         struct scsi_cmnd *sc = ctask->sc;
707         struct scatterlist *sg;
708         int i, offset, rc = 0;
709
710         BUG_ON((void*)ctask != sc->SCp.ptr);
711
712         /*
713          * copying Data-In into the Scsi_Cmnd
714          */
715         if (!sc->use_sg) {
716                 i = ctask->data_count;
717                 rc = iscsi_ctask_copy(tcp_conn, ctask, sc->request_buffer,
718                                       sc->request_bufflen,
719                                       tcp_ctask->data_offset);
720                 if (rc == -EAGAIN)
721                         return rc;
722                 if (conn->datadgst_en)
723                         iscsi_recv_digest_update(tcp_conn, sc->request_buffer,
724                                                  i);
725                 rc = 0;
726                 goto done;
727         }
728
729         offset = tcp_ctask->data_offset;
730         sg = sc->request_buffer;
731
732         if (tcp_ctask->data_offset)
733                 for (i = 0; i < tcp_ctask->sg_count; i++)
734                         offset -= sg[i].length;
735         /* we've passed through partial sg*/
736         if (offset < 0)
737                 offset = 0;
738
739         for (i = tcp_ctask->sg_count; i < sc->use_sg; i++) {
740                 char *dest;
741
742                 dest = kmap_atomic(sg[i].page, KM_SOFTIRQ0);
743                 rc = iscsi_ctask_copy(tcp_conn, ctask, dest + sg[i].offset,
744                                       sg[i].length, offset);
745                 kunmap_atomic(dest, KM_SOFTIRQ0);
746                 if (rc == -EAGAIN)
747                         /* continue with the next SKB/PDU */
748                         return rc;
749                 if (!rc) {
750                         if (conn->datadgst_en) {
751                                 if (!offset)
752                                         crypto_hash_update(
753                                                         &tcp_conn->rx_hash,
754                                                         &sg[i], sg[i].length);
755                                 else
756                                         partial_sg_digest_update(
757                                                         &tcp_conn->rx_hash,
758                                                         &sg[i],
759                                                         sg[i].offset + offset,
760                                                         sg[i].length - offset);
761                         }
762                         offset = 0;
763                         tcp_ctask->sg_count++;
764                 }
765
766                 if (!ctask->data_count) {
767                         if (rc && conn->datadgst_en)
768                                 /*
769                                  * data-in is complete, but buffer not...
770                                  */
771                                 partial_sg_digest_update(&tcp_conn->rx_hash,
772                                                          &sg[i],
773                                                          sg[i].offset,
774                                                          sg[i].length-rc);
775                         rc = 0;
776                         break;
777                 }
778
779                 if (!tcp_conn->in.copy)
780                         return -EAGAIN;
781         }
782         BUG_ON(ctask->data_count);
783
784 done:
785         /* check for non-exceptional status */
786         if (tcp_conn->in.hdr->flags & ISCSI_FLAG_DATA_STATUS) {
787                 debug_scsi("done [sc %lx res %d itt 0x%x flags 0x%x]\n",
788                            (long)sc, sc->result, ctask->itt,
789                            tcp_conn->in.hdr->flags);
790                 spin_lock(&conn->session->lock);
791                 __iscsi_complete_pdu(conn, tcp_conn->in.hdr, NULL, 0);
792                 spin_unlock(&conn->session->lock);
793         }
794
795         return rc;
796 }
797
798 static int
799 iscsi_data_recv(struct iscsi_conn *conn)
800 {
801         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
802         int rc = 0, opcode;
803
804         opcode = tcp_conn->in.hdr->opcode & ISCSI_OPCODE_MASK;
805         switch (opcode) {
806         case ISCSI_OP_SCSI_DATA_IN:
807                 rc = iscsi_scsi_data_in(conn);
808                 break;
809         case ISCSI_OP_SCSI_CMD_RSP:
810         case ISCSI_OP_TEXT_RSP:
811         case ISCSI_OP_LOGIN_RSP:
812         case ISCSI_OP_ASYNC_EVENT:
813         case ISCSI_OP_REJECT:
814                 /*
815                  * Collect data segment to the connection's data
816                  * placeholder
817                  */
818                 if (iscsi_tcp_copy(conn, tcp_conn->in.datalen)) {
819                         rc = -EAGAIN;
820                         goto exit;
821                 }
822
823                 rc = iscsi_complete_pdu(conn, tcp_conn->in.hdr, conn->data,
824                                         tcp_conn->in.datalen);
825                 if (!rc && conn->datadgst_en && opcode != ISCSI_OP_LOGIN_RSP)
826                         iscsi_recv_digest_update(tcp_conn, conn->data,
827                                                 tcp_conn->in.datalen);
828                 break;
829         default:
830                 BUG_ON(1);
831         }
832 exit:
833         return rc;
834 }
835
836 /**
837  * iscsi_tcp_data_recv - TCP receive in sendfile fashion
838  * @rd_desc: read descriptor
839  * @skb: socket buffer
840  * @offset: offset in skb
841  * @len: skb->len - offset
842  **/
843 static int
844 iscsi_tcp_data_recv(read_descriptor_t *rd_desc, struct sk_buff *skb,
845                 unsigned int offset, size_t len)
846 {
847         int rc;
848         struct iscsi_conn *conn = rd_desc->arg.data;
849         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
850         int processed;
851         char pad[ISCSI_PAD_LEN];
852         struct scatterlist sg;
853
854         /*
855          * Save current SKB and its offset in the corresponding
856          * connection context.
857          */
858         tcp_conn->in.copy = skb->len - offset;
859         tcp_conn->in.offset = offset;
860         tcp_conn->in.skb = skb;
861         tcp_conn->in.len = tcp_conn->in.copy;
862         BUG_ON(tcp_conn->in.copy <= 0);
863         debug_tcp("in %d bytes\n", tcp_conn->in.copy);
864
865 more:
866         tcp_conn->in.copied = 0;
867         rc = 0;
868
869         if (unlikely(conn->suspend_rx)) {
870                 debug_tcp("conn %d Rx suspended!\n", conn->id);
871                 return 0;
872         }
873
874         if (tcp_conn->in_progress == IN_PROGRESS_WAIT_HEADER ||
875             tcp_conn->in_progress == IN_PROGRESS_HEADER_GATHER) {
876                 rc = iscsi_hdr_extract(tcp_conn);
877                 if (rc) {
878                        if (rc == -EAGAIN)
879                                 goto nomore;
880                        else {
881                                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
882                                 return 0;
883                        }
884                 }
885
886                 /*
887                  * Verify and process incoming PDU header.
888                  */
889                 rc = iscsi_tcp_hdr_recv(conn);
890                 if (!rc && tcp_conn->in.datalen) {
891                         if (conn->datadgst_en)
892                                 crypto_hash_init(&tcp_conn->rx_hash);
893                         tcp_conn->in_progress = IN_PROGRESS_DATA_RECV;
894                 } else if (rc) {
895                         iscsi_conn_failure(conn, rc);
896                         return 0;
897                 }
898         }
899
900         if (tcp_conn->in_progress == IN_PROGRESS_DDIGEST_RECV &&
901             tcp_conn->in.copy) {
902                 uint32_t recv_digest;
903
904                 debug_tcp("extra data_recv offset %d copy %d\n",
905                           tcp_conn->in.offset, tcp_conn->in.copy);
906
907                 if (!tcp_conn->data_copied) {
908                         if (tcp_conn->in.padding) {
909                                 debug_tcp("padding -> %d\n",
910                                           tcp_conn->in.padding);
911                                 memset(pad, 0, tcp_conn->in.padding);
912                                 sg_init_one(&sg, pad, tcp_conn->in.padding);
913                                 crypto_hash_update(&tcp_conn->rx_hash,
914                                                    &sg, sg.length);
915                         }
916                         crypto_hash_final(&tcp_conn->rx_hash,
917                                           (u8 *) &tcp_conn->in.datadgst);
918                         debug_tcp("rx digest 0x%x\n", tcp_conn->in.datadgst);
919                 }
920
921                 rc = iscsi_tcp_copy(conn, sizeof(uint32_t));
922                 if (rc) {
923                         if (rc == -EAGAIN)
924                                 goto again;
925                         iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
926                         return 0;
927                 }
928
929                 memcpy(&recv_digest, conn->data, sizeof(uint32_t));
930                 if (recv_digest != tcp_conn->in.datadgst) {
931                         debug_tcp("iscsi_tcp: data digest error!"
932                                   "0x%x != 0x%x\n", recv_digest,
933                                   tcp_conn->in.datadgst);
934                         iscsi_conn_failure(conn, ISCSI_ERR_DATA_DGST);
935                         return 0;
936                 } else {
937                         debug_tcp("iscsi_tcp: data digest match!"
938                                   "0x%x == 0x%x\n", recv_digest,
939                                   tcp_conn->in.datadgst);
940                         tcp_conn->in_progress = IN_PROGRESS_WAIT_HEADER;
941                 }
942         }
943
944         if (tcp_conn->in_progress == IN_PROGRESS_DATA_RECV &&
945             tcp_conn->in.copy) {
946                 debug_tcp("data_recv offset %d copy %d\n",
947                        tcp_conn->in.offset, tcp_conn->in.copy);
948
949                 rc = iscsi_data_recv(conn);
950                 if (rc) {
951                         if (rc == -EAGAIN)
952                                 goto again;
953                         iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
954                         return 0;
955                 }
956
957                 if (tcp_conn->in.padding)
958                         tcp_conn->in_progress = IN_PROGRESS_PAD_RECV;
959                 else if (conn->datadgst_en)
960                         tcp_conn->in_progress = IN_PROGRESS_DDIGEST_RECV;
961                 else
962                         tcp_conn->in_progress = IN_PROGRESS_WAIT_HEADER;
963                 tcp_conn->data_copied = 0;
964         }
965
966         if (tcp_conn->in_progress == IN_PROGRESS_PAD_RECV &&
967             tcp_conn->in.copy) {
968                 int copylen = min(tcp_conn->in.padding - tcp_conn->data_copied,
969                                   tcp_conn->in.copy);
970
971                 tcp_conn->in.copy -= copylen;
972                 tcp_conn->in.offset += copylen;
973                 tcp_conn->data_copied += copylen;
974
975                 if (tcp_conn->data_copied != tcp_conn->in.padding)
976                         tcp_conn->in_progress = IN_PROGRESS_PAD_RECV;
977                 else if (conn->datadgst_en)
978                         tcp_conn->in_progress = IN_PROGRESS_DDIGEST_RECV;
979                 else
980                         tcp_conn->in_progress = IN_PROGRESS_WAIT_HEADER;
981                 tcp_conn->data_copied = 0;
982         }
983
984         debug_tcp("f, processed %d from out of %d padding %d\n",
985                tcp_conn->in.offset - offset, (int)len, tcp_conn->in.padding);
986         BUG_ON(tcp_conn->in.offset - offset > len);
987
988         if (tcp_conn->in.offset - offset != len) {
989                 debug_tcp("continue to process %d bytes\n",
990                        (int)len - (tcp_conn->in.offset - offset));
991                 goto more;
992         }
993
994 nomore:
995         processed = tcp_conn->in.offset - offset;
996         BUG_ON(processed == 0);
997         return processed;
998
999 again:
1000         processed = tcp_conn->in.offset - offset;
1001         debug_tcp("c, processed %d from out of %d rd_desc_cnt %d\n",
1002                   processed, (int)len, (int)rd_desc->count);
1003         BUG_ON(processed == 0);
1004         BUG_ON(processed > len);
1005
1006         conn->rxdata_octets += processed;
1007         return processed;
1008 }
1009
1010 static void
1011 iscsi_tcp_data_ready(struct sock *sk, int flag)
1012 {
1013         struct iscsi_conn *conn = sk->sk_user_data;
1014         read_descriptor_t rd_desc;
1015
1016         read_lock(&sk->sk_callback_lock);
1017
1018         /*
1019          * Use rd_desc to pass 'conn' to iscsi_tcp_data_recv.
1020          * We set count to 1 because we want the network layer to
1021          * hand us all the skbs that are available. iscsi_tcp_data_recv
1022          * handled pdus that cross buffers or pdus that still need data.
1023          */
1024         rd_desc.arg.data = conn;
1025         rd_desc.count = 1;
1026         tcp_read_sock(sk, &rd_desc, iscsi_tcp_data_recv);
1027
1028         read_unlock(&sk->sk_callback_lock);
1029 }
1030
1031 static void
1032 iscsi_tcp_state_change(struct sock *sk)
1033 {
1034         struct iscsi_tcp_conn *tcp_conn;
1035         struct iscsi_conn *conn;
1036         struct iscsi_session *session;
1037         void (*old_state_change)(struct sock *);
1038
1039         read_lock(&sk->sk_callback_lock);
1040
1041         conn = (struct iscsi_conn*)sk->sk_user_data;
1042         session = conn->session;
1043
1044         if ((sk->sk_state == TCP_CLOSE_WAIT ||
1045              sk->sk_state == TCP_CLOSE) &&
1046             !atomic_read(&sk->sk_rmem_alloc)) {
1047                 debug_tcp("iscsi_tcp_state_change: TCP_CLOSE|TCP_CLOSE_WAIT\n");
1048                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1049         }
1050
1051         tcp_conn = conn->dd_data;
1052         old_state_change = tcp_conn->old_state_change;
1053
1054         read_unlock(&sk->sk_callback_lock);
1055
1056         old_state_change(sk);
1057 }
1058
1059 /**
1060  * iscsi_write_space - Called when more output buffer space is available
1061  * @sk: socket space is available for
1062  **/
1063 static void
1064 iscsi_write_space(struct sock *sk)
1065 {
1066         struct iscsi_conn *conn = (struct iscsi_conn*)sk->sk_user_data;
1067         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1068
1069         tcp_conn->old_write_space(sk);
1070         debug_tcp("iscsi_write_space: cid %d\n", conn->id);
1071         scsi_queue_work(conn->session->host, &conn->xmitwork);
1072 }
1073
1074 static void
1075 iscsi_conn_set_callbacks(struct iscsi_conn *conn)
1076 {
1077         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1078         struct sock *sk = tcp_conn->sock->sk;
1079
1080         /* assign new callbacks */
1081         write_lock_bh(&sk->sk_callback_lock);
1082         sk->sk_user_data = conn;
1083         tcp_conn->old_data_ready = sk->sk_data_ready;
1084         tcp_conn->old_state_change = sk->sk_state_change;
1085         tcp_conn->old_write_space = sk->sk_write_space;
1086         sk->sk_data_ready = iscsi_tcp_data_ready;
1087         sk->sk_state_change = iscsi_tcp_state_change;
1088         sk->sk_write_space = iscsi_write_space;
1089         write_unlock_bh(&sk->sk_callback_lock);
1090 }
1091
1092 static void
1093 iscsi_conn_restore_callbacks(struct iscsi_tcp_conn *tcp_conn)
1094 {
1095         struct sock *sk = tcp_conn->sock->sk;
1096
1097         /* restore socket callbacks, see also: iscsi_conn_set_callbacks() */
1098         write_lock_bh(&sk->sk_callback_lock);
1099         sk->sk_user_data    = NULL;
1100         sk->sk_data_ready   = tcp_conn->old_data_ready;
1101         sk->sk_state_change = tcp_conn->old_state_change;
1102         sk->sk_write_space  = tcp_conn->old_write_space;
1103         sk->sk_no_check  = 0;
1104         write_unlock_bh(&sk->sk_callback_lock);
1105 }
1106
1107 /**
1108  * iscsi_send - generic send routine
1109  * @sk: kernel's socket
1110  * @buf: buffer to write from
1111  * @size: actual size to write
1112  * @flags: socket's flags
1113  */
1114 static inline int
1115 iscsi_send(struct iscsi_conn *conn, struct iscsi_buf *buf, int size, int flags)
1116 {
1117         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1118         struct socket *sk = tcp_conn->sock;
1119         int offset = buf->sg.offset + buf->sent, res;
1120
1121         /*
1122          * if we got use_sg=0 or are sending something we kmallocd
1123          * then we did not have to do kmap (kmap returns page_address)
1124          *
1125          * if we got use_sg > 0, but had to drop down, we do not
1126          * set clustering so this should only happen for that
1127          * slab case.
1128          */
1129         if (buf->use_sendmsg)
1130                 res = sock_no_sendpage(sk, buf->sg.page, offset, size, flags);
1131         else
1132                 res = tcp_conn->sendpage(sk, buf->sg.page, offset, size, flags);
1133
1134         if (res >= 0) {
1135                 conn->txdata_octets += res;
1136                 buf->sent += res;
1137                 return res;
1138         }
1139
1140         tcp_conn->sendpage_failures_cnt++;
1141         if (res == -EAGAIN)
1142                 res = -ENOBUFS;
1143         else
1144                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1145         return res;
1146 }
1147
1148 /**
1149  * iscsi_sendhdr - send PDU Header via tcp_sendpage()
1150  * @conn: iscsi connection
1151  * @buf: buffer to write from
1152  * @datalen: lenght of data to be sent after the header
1153  *
1154  * Notes:
1155  *      (Tx, Fast Path)
1156  **/
1157 static inline int
1158 iscsi_sendhdr(struct iscsi_conn *conn, struct iscsi_buf *buf, int datalen)
1159 {
1160         int flags = 0; /* MSG_DONTWAIT; */
1161         int res, size;
1162
1163         size = buf->sg.length - buf->sent;
1164         BUG_ON(buf->sent + size > buf->sg.length);
1165         if (buf->sent + size != buf->sg.length || datalen)
1166                 flags |= MSG_MORE;
1167
1168         res = iscsi_send(conn, buf, size, flags);
1169         debug_tcp("sendhdr %d bytes, sent %d res %d\n", size, buf->sent, res);
1170         if (res >= 0) {
1171                 if (size != res)
1172                         return -EAGAIN;
1173                 return 0;
1174         }
1175
1176         return res;
1177 }
1178
1179 /**
1180  * iscsi_sendpage - send one page of iSCSI Data-Out.
1181  * @conn: iscsi connection
1182  * @buf: buffer to write from
1183  * @count: remaining data
1184  * @sent: number of bytes sent
1185  *
1186  * Notes:
1187  *      (Tx, Fast Path)
1188  **/
1189 static inline int
1190 iscsi_sendpage(struct iscsi_conn *conn, struct iscsi_buf *buf,
1191                int *count, int *sent)
1192 {
1193         int flags = 0; /* MSG_DONTWAIT; */
1194         int res, size;
1195
1196         size = buf->sg.length - buf->sent;
1197         BUG_ON(buf->sent + size > buf->sg.length);
1198         if (size > *count)
1199                 size = *count;
1200         if (buf->sent + size != buf->sg.length || *count != size)
1201                 flags |= MSG_MORE;
1202
1203         res = iscsi_send(conn, buf, size, flags);
1204         debug_tcp("sendpage: %d bytes, sent %d left %d sent %d res %d\n",
1205                   size, buf->sent, *count, *sent, res);
1206         if (res >= 0) {
1207                 *count -= res;
1208                 *sent += res;
1209                 if (size != res)
1210                         return -EAGAIN;
1211                 return 0;
1212         }
1213
1214         return res;
1215 }
1216
1217 static inline void
1218 iscsi_data_digest_init(struct iscsi_tcp_conn *tcp_conn,
1219                       struct iscsi_tcp_cmd_task *tcp_ctask)
1220 {
1221         crypto_hash_init(&tcp_conn->tx_hash);
1222         tcp_ctask->digest_count = 4;
1223 }
1224
1225 /**
1226  * iscsi_solicit_data_cont - initialize next Data-Out
1227  * @conn: iscsi connection
1228  * @ctask: scsi command task
1229  * @r2t: R2T info
1230  * @left: bytes left to transfer
1231  *
1232  * Notes:
1233  *      Initialize next Data-Out within this R2T sequence and continue
1234  *      to process next Scatter-Gather element(if any) of this SCSI command.
1235  *
1236  *      Called under connection lock.
1237  **/
1238 static void
1239 iscsi_solicit_data_cont(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask,
1240                         struct iscsi_r2t_info *r2t, int left)
1241 {
1242         struct iscsi_data *hdr;
1243         struct scsi_cmnd *sc = ctask->sc;
1244         int new_offset;
1245
1246         hdr = &r2t->dtask.hdr;
1247         memset(hdr, 0, sizeof(struct iscsi_data));
1248         hdr->ttt = r2t->ttt;
1249         hdr->datasn = cpu_to_be32(r2t->solicit_datasn);
1250         r2t->solicit_datasn++;
1251         hdr->opcode = ISCSI_OP_SCSI_DATA_OUT;
1252         memcpy(hdr->lun, ctask->hdr->lun, sizeof(hdr->lun));
1253         hdr->itt = ctask->hdr->itt;
1254         hdr->exp_statsn = r2t->exp_statsn;
1255         new_offset = r2t->data_offset + r2t->sent;
1256         hdr->offset = cpu_to_be32(new_offset);
1257         if (left > conn->max_xmit_dlength) {
1258                 hton24(hdr->dlength, conn->max_xmit_dlength);
1259                 r2t->data_count = conn->max_xmit_dlength;
1260         } else {
1261                 hton24(hdr->dlength, left);
1262                 r2t->data_count = left;
1263                 hdr->flags = ISCSI_FLAG_CMD_FINAL;
1264         }
1265         conn->dataout_pdus_cnt++;
1266
1267         iscsi_buf_init_iov(&r2t->headbuf, (char*)hdr,
1268                            sizeof(struct iscsi_hdr));
1269
1270         if (iscsi_buf_left(&r2t->sendbuf))
1271                 return;
1272
1273         if (sc->use_sg) {
1274                 iscsi_buf_init_sg(&r2t->sendbuf, r2t->sg);
1275                 r2t->sg += 1;
1276         } else {
1277                 iscsi_buf_init_iov(&r2t->sendbuf,
1278                             (char*)sc->request_buffer + new_offset,
1279                             r2t->data_count);
1280                 r2t->sg = NULL;
1281         }
1282 }
1283
1284 static void iscsi_set_padding(struct iscsi_tcp_cmd_task *tcp_ctask,
1285                               unsigned long len)
1286 {
1287         tcp_ctask->pad_count = len & (ISCSI_PAD_LEN - 1);
1288         if (!tcp_ctask->pad_count)
1289                 return;
1290
1291         tcp_ctask->pad_count = ISCSI_PAD_LEN - tcp_ctask->pad_count;
1292         debug_scsi("write padding %d bytes\n", tcp_ctask->pad_count);
1293         tcp_ctask->xmstate |= XMSTATE_W_PAD;
1294 }
1295
1296 /**
1297  * iscsi_tcp_cmd_init - Initialize iSCSI SCSI_READ or SCSI_WRITE commands
1298  * @conn: iscsi connection
1299  * @ctask: scsi command task
1300  * @sc: scsi command
1301  **/
1302 static void
1303 iscsi_tcp_cmd_init(struct iscsi_cmd_task *ctask)
1304 {
1305         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1306
1307         BUG_ON(__kfifo_len(tcp_ctask->r2tqueue));
1308         tcp_ctask->xmstate = XMSTATE_CMD_HDR_INIT;
1309 }
1310
1311 /**
1312  * iscsi_tcp_mtask_xmit - xmit management(immediate) task
1313  * @conn: iscsi connection
1314  * @mtask: task management task
1315  *
1316  * Notes:
1317  *      The function can return -EAGAIN in which case caller must
1318  *      call it again later, or recover. '0' return code means successful
1319  *      xmit.
1320  *
1321  *      Management xmit state machine consists of these states:
1322  *              XMSTATE_IMM_HDR_INIT    - calculate digest of PDU Header
1323  *              XMSTATE_IMM_HDR         - PDU Header xmit in progress
1324  *              XMSTATE_IMM_DATA        - PDU Data xmit in progress
1325  *              XMSTATE_IDLE            - management PDU is done
1326  **/
1327 static int
1328 iscsi_tcp_mtask_xmit(struct iscsi_conn *conn, struct iscsi_mgmt_task *mtask)
1329 {
1330         struct iscsi_tcp_mgmt_task *tcp_mtask = mtask->dd_data;
1331         int rc;
1332
1333         debug_scsi("mtask deq [cid %d state %x itt 0x%x]\n",
1334                 conn->id, tcp_mtask->xmstate, mtask->itt);
1335
1336         if (tcp_mtask->xmstate & XMSTATE_IMM_HDR_INIT) {
1337                 iscsi_buf_init_iov(&tcp_mtask->headbuf, (char*)mtask->hdr,
1338                                    sizeof(struct iscsi_hdr));
1339
1340                 if (mtask->data_count) {
1341                         tcp_mtask->xmstate |= XMSTATE_IMM_DATA;
1342                         iscsi_buf_init_iov(&tcp_mtask->sendbuf,
1343                                            (char*)mtask->data,
1344                                            mtask->data_count);
1345                 }
1346
1347                 if (conn->c_stage != ISCSI_CONN_INITIAL_STAGE &&
1348                     conn->stop_stage != STOP_CONN_RECOVER &&
1349                     conn->hdrdgst_en)
1350                         iscsi_hdr_digest(conn, &tcp_mtask->headbuf,
1351                                         (u8*)tcp_mtask->hdrext);
1352
1353                 tcp_mtask->sent = 0;
1354                 tcp_mtask->xmstate &= ~XMSTATE_IMM_HDR_INIT;
1355                 tcp_mtask->xmstate |= XMSTATE_IMM_HDR;
1356         }
1357
1358         if (tcp_mtask->xmstate & XMSTATE_IMM_HDR) {
1359                 rc = iscsi_sendhdr(conn, &tcp_mtask->headbuf,
1360                                    mtask->data_count);
1361                 if (rc)
1362                         return rc;
1363                 tcp_mtask->xmstate &= ~XMSTATE_IMM_HDR;
1364         }
1365
1366         if (tcp_mtask->xmstate & XMSTATE_IMM_DATA) {
1367                 BUG_ON(!mtask->data_count);
1368                 tcp_mtask->xmstate &= ~XMSTATE_IMM_DATA;
1369                 /* FIXME: implement.
1370                  * Virtual buffer could be spreaded across multiple pages...
1371                  */
1372                 do {
1373                         int rc;
1374
1375                         rc = iscsi_sendpage(conn, &tcp_mtask->sendbuf,
1376                                         &mtask->data_count, &tcp_mtask->sent);
1377                         if (rc) {
1378                                 tcp_mtask->xmstate |= XMSTATE_IMM_DATA;
1379                                 return rc;
1380                         }
1381                 } while (mtask->data_count);
1382         }
1383
1384         BUG_ON(tcp_mtask->xmstate != XMSTATE_IDLE);
1385         if (mtask->hdr->itt == RESERVED_ITT) {
1386                 struct iscsi_session *session = conn->session;
1387
1388                 spin_lock_bh(&session->lock);
1389                 list_del(&conn->mtask->running);
1390                 __kfifo_put(session->mgmtpool.queue, (void*)&conn->mtask,
1391                             sizeof(void*));
1392                 spin_unlock_bh(&session->lock);
1393         }
1394         return 0;
1395 }
1396
1397 static int
1398 iscsi_send_cmd_hdr(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
1399 {
1400         struct scsi_cmnd *sc = ctask->sc;
1401         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1402         int rc = 0;
1403
1404         if (tcp_ctask->xmstate & XMSTATE_CMD_HDR_INIT) {
1405                 tcp_ctask->sent = 0;
1406                 tcp_ctask->sg_count = 0;
1407                 tcp_ctask->exp_datasn = 0;
1408
1409                 if (sc->sc_data_direction == DMA_TO_DEVICE) {
1410                         if (sc->use_sg) {
1411                                 struct scatterlist *sg = sc->request_buffer;
1412
1413                                 iscsi_buf_init_sg(&tcp_ctask->sendbuf, sg);
1414                                 tcp_ctask->sg = sg + 1;
1415                                 tcp_ctask->bad_sg = sg + sc->use_sg;
1416                         } else {
1417                                 iscsi_buf_init_iov(&tcp_ctask->sendbuf,
1418                                                    sc->request_buffer,
1419                                                    sc->request_bufflen);
1420                                 tcp_ctask->sg = NULL;
1421                                 tcp_ctask->bad_sg = NULL;
1422                         }
1423
1424                         debug_scsi("cmd [itt 0x%x total %d imm_data %d "
1425                                    "unsol count %d, unsol offset %d]\n",
1426                                    ctask->itt, sc->request_bufflen,
1427                                    ctask->imm_count, ctask->unsol_count,
1428                                    ctask->unsol_offset);
1429                 }
1430
1431                 iscsi_buf_init_iov(&tcp_ctask->headbuf, (char*)ctask->hdr,
1432                                   sizeof(struct iscsi_hdr));
1433
1434                 if (conn->hdrdgst_en)
1435                         iscsi_hdr_digest(conn, &tcp_ctask->headbuf,
1436                                          (u8*)tcp_ctask->hdrext);
1437                 tcp_ctask->xmstate &= ~XMSTATE_CMD_HDR_INIT;
1438                 tcp_ctask->xmstate |= XMSTATE_CMD_HDR_XMIT;
1439         }
1440
1441         if (tcp_ctask->xmstate & XMSTATE_CMD_HDR_XMIT) {
1442                 rc = iscsi_sendhdr(conn, &tcp_ctask->headbuf, ctask->imm_count);
1443                 if (rc)
1444                         return rc;
1445                 tcp_ctask->xmstate &= ~XMSTATE_CMD_HDR_XMIT;
1446
1447                 if (sc->sc_data_direction != DMA_TO_DEVICE)
1448                         return 0;
1449
1450                 if (ctask->imm_count) {
1451                         tcp_ctask->xmstate |= XMSTATE_IMM_DATA;
1452                         iscsi_set_padding(tcp_ctask, ctask->imm_count);
1453
1454                         if (ctask->conn->datadgst_en) {
1455                                 iscsi_data_digest_init(ctask->conn->dd_data,
1456                                                        tcp_ctask);
1457                                 tcp_ctask->immdigest = 0;
1458                         }
1459                 }
1460
1461                 if (ctask->unsol_count)
1462                         tcp_ctask->xmstate |=
1463                                         XMSTATE_UNS_HDR | XMSTATE_UNS_INIT;
1464         }
1465         return rc;
1466 }
1467
1468 static int
1469 iscsi_send_padding(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
1470 {
1471         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1472         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1473         int sent = 0, rc;
1474
1475         if (tcp_ctask->xmstate & XMSTATE_W_PAD) {
1476                 iscsi_buf_init_iov(&tcp_ctask->sendbuf, (char*)&tcp_ctask->pad,
1477                                    tcp_ctask->pad_count);
1478                 if (conn->datadgst_en)
1479                         crypto_hash_update(&tcp_conn->tx_hash,
1480                                            &tcp_ctask->sendbuf.sg,
1481                                            tcp_ctask->sendbuf.sg.length);
1482         } else if (!(tcp_ctask->xmstate & XMSTATE_W_RESEND_PAD))
1483                 return 0;
1484
1485         tcp_ctask->xmstate &= ~XMSTATE_W_PAD;
1486         tcp_ctask->xmstate &= ~XMSTATE_W_RESEND_PAD;
1487         debug_scsi("sending %d pad bytes for itt 0x%x\n",
1488                    tcp_ctask->pad_count, ctask->itt);
1489         rc = iscsi_sendpage(conn, &tcp_ctask->sendbuf, &tcp_ctask->pad_count,
1490                            &sent);
1491         if (rc) {
1492                 debug_scsi("padding send failed %d\n", rc);
1493                 tcp_ctask->xmstate |= XMSTATE_W_RESEND_PAD;
1494         }
1495         return rc;
1496 }
1497
1498 static int
1499 iscsi_send_digest(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask,
1500                         struct iscsi_buf *buf, uint32_t *digest)
1501 {
1502         struct iscsi_tcp_cmd_task *tcp_ctask;
1503         struct iscsi_tcp_conn *tcp_conn;
1504         int rc, sent = 0;
1505
1506         if (!conn->datadgst_en)
1507                 return 0;
1508
1509         tcp_ctask = ctask->dd_data;
1510         tcp_conn = conn->dd_data;
1511
1512         if (!(tcp_ctask->xmstate & XMSTATE_W_RESEND_DATA_DIGEST)) {
1513                 crypto_hash_final(&tcp_conn->tx_hash, (u8*)digest);
1514                 iscsi_buf_init_iov(buf, (char*)digest, 4);
1515         }
1516         tcp_ctask->xmstate &= ~XMSTATE_W_RESEND_DATA_DIGEST;
1517
1518         rc = iscsi_sendpage(conn, buf, &tcp_ctask->digest_count, &sent);
1519         if (!rc)
1520                 debug_scsi("sent digest 0x%x for itt 0x%x\n", *digest,
1521                           ctask->itt);
1522         else {
1523                 debug_scsi("sending digest 0x%x failed for itt 0x%x!\n",
1524                           *digest, ctask->itt);
1525                 tcp_ctask->xmstate |= XMSTATE_W_RESEND_DATA_DIGEST;
1526         }
1527         return rc;
1528 }
1529
1530 static int
1531 iscsi_send_data(struct iscsi_cmd_task *ctask, struct iscsi_buf *sendbuf,
1532                 struct scatterlist **sg, int *sent, int *count,
1533                 struct iscsi_buf *digestbuf, uint32_t *digest)
1534 {
1535         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1536         struct iscsi_conn *conn = ctask->conn;
1537         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1538         int rc, buf_sent, offset;
1539
1540         while (*count) {
1541                 buf_sent = 0;
1542                 offset = sendbuf->sent;
1543
1544                 rc = iscsi_sendpage(conn, sendbuf, count, &buf_sent);
1545                 *sent = *sent + buf_sent;
1546                 if (buf_sent && conn->datadgst_en)
1547                         partial_sg_digest_update(&tcp_conn->tx_hash,
1548                                 &sendbuf->sg, sendbuf->sg.offset + offset,
1549                                 buf_sent);
1550                 if (!iscsi_buf_left(sendbuf) && *sg != tcp_ctask->bad_sg) {
1551                         iscsi_buf_init_sg(sendbuf, *sg);
1552                         *sg = *sg + 1;
1553                 }
1554
1555                 if (rc)
1556                         return rc;
1557         }
1558
1559         rc = iscsi_send_padding(conn, ctask);
1560         if (rc)
1561                 return rc;
1562
1563         return iscsi_send_digest(conn, ctask, digestbuf, digest);
1564 }
1565
1566 static int
1567 iscsi_send_unsol_hdr(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
1568 {
1569         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1570         struct iscsi_data_task *dtask;
1571         int rc;
1572
1573         tcp_ctask->xmstate |= XMSTATE_UNS_DATA;
1574         if (tcp_ctask->xmstate & XMSTATE_UNS_INIT) {
1575                 dtask = &tcp_ctask->unsol_dtask;
1576
1577                 iscsi_prep_unsolicit_data_pdu(ctask, &dtask->hdr);
1578                 iscsi_buf_init_iov(&tcp_ctask->headbuf, (char*)&dtask->hdr,
1579                                    sizeof(struct iscsi_hdr));
1580                 if (conn->hdrdgst_en)
1581                         iscsi_hdr_digest(conn, &tcp_ctask->headbuf,
1582                                         (u8*)dtask->hdrext);
1583
1584                 tcp_ctask->xmstate &= ~XMSTATE_UNS_INIT;
1585                 iscsi_set_padding(tcp_ctask, ctask->data_count);
1586         }
1587
1588         rc = iscsi_sendhdr(conn, &tcp_ctask->headbuf, ctask->data_count);
1589         if (rc) {
1590                 tcp_ctask->xmstate &= ~XMSTATE_UNS_DATA;
1591                 tcp_ctask->xmstate |= XMSTATE_UNS_HDR;
1592                 return rc;
1593         }
1594
1595         if (conn->datadgst_en) {
1596                 dtask = &tcp_ctask->unsol_dtask;
1597                 iscsi_data_digest_init(ctask->conn->dd_data, tcp_ctask);
1598                 dtask->digest = 0;
1599         }
1600
1601         debug_scsi("uns dout [itt 0x%x dlen %d sent %d]\n",
1602                    ctask->itt, ctask->unsol_count, tcp_ctask->sent);
1603         return 0;
1604 }
1605
1606 static int
1607 iscsi_send_unsol_pdu(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
1608 {
1609         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1610         int rc;
1611
1612         if (tcp_ctask->xmstate & XMSTATE_UNS_HDR) {
1613                 BUG_ON(!ctask->unsol_count);
1614                 tcp_ctask->xmstate &= ~XMSTATE_UNS_HDR;
1615 send_hdr:
1616                 rc = iscsi_send_unsol_hdr(conn, ctask);
1617                 if (rc)
1618                         return rc;
1619         }
1620
1621         if (tcp_ctask->xmstate & XMSTATE_UNS_DATA) {
1622                 struct iscsi_data_task *dtask = &tcp_ctask->unsol_dtask;
1623                 int start = tcp_ctask->sent;
1624
1625                 rc = iscsi_send_data(ctask, &tcp_ctask->sendbuf, &tcp_ctask->sg,
1626                                      &tcp_ctask->sent, &ctask->data_count,
1627                                      &dtask->digestbuf, &dtask->digest);
1628                 ctask->unsol_count -= tcp_ctask->sent - start;
1629                 if (rc)
1630                         return rc;
1631                 tcp_ctask->xmstate &= ~XMSTATE_UNS_DATA;
1632                 /*
1633                  * Done with the Data-Out. Next, check if we need
1634                  * to send another unsolicited Data-Out.
1635                  */
1636                 if (ctask->unsol_count) {
1637                         debug_scsi("sending more uns\n");
1638                         tcp_ctask->xmstate |= XMSTATE_UNS_INIT;
1639                         goto send_hdr;
1640                 }
1641         }
1642         return 0;
1643 }
1644
1645 static int iscsi_send_sol_pdu(struct iscsi_conn *conn,
1646                               struct iscsi_cmd_task *ctask)
1647 {
1648         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1649         struct iscsi_session *session = conn->session;
1650         struct iscsi_r2t_info *r2t;
1651         struct iscsi_data_task *dtask;
1652         int left, rc;
1653
1654         if (tcp_ctask->xmstate & XMSTATE_SOL_HDR_INIT) {
1655                 if (!tcp_ctask->r2t) {
1656                         spin_lock_bh(&session->lock);
1657                         __kfifo_get(tcp_ctask->r2tqueue, (void*)&tcp_ctask->r2t,
1658                                     sizeof(void*));
1659                         spin_unlock_bh(&session->lock);
1660                 }
1661 send_hdr:
1662                 r2t = tcp_ctask->r2t;
1663                 dtask = &r2t->dtask;
1664
1665                 if (conn->hdrdgst_en)
1666                         iscsi_hdr_digest(conn, &r2t->headbuf,
1667                                         (u8*)dtask->hdrext);
1668                 tcp_ctask->xmstate &= ~XMSTATE_SOL_HDR_INIT;
1669                 tcp_ctask->xmstate |= XMSTATE_SOL_HDR;
1670         }
1671
1672         if (tcp_ctask->xmstate & XMSTATE_SOL_HDR) {
1673                 r2t = tcp_ctask->r2t;
1674                 dtask = &r2t->dtask;
1675
1676                 rc = iscsi_sendhdr(conn, &r2t->headbuf, r2t->data_count);
1677                 if (rc)
1678                         return rc;
1679                 tcp_ctask->xmstate &= ~XMSTATE_SOL_HDR;
1680                 tcp_ctask->xmstate |= XMSTATE_SOL_DATA;
1681
1682                 if (conn->datadgst_en) {
1683                         iscsi_data_digest_init(conn->dd_data, tcp_ctask);
1684                         dtask->digest = 0;
1685                 }
1686
1687                 iscsi_set_padding(tcp_ctask, r2t->data_count);
1688                 debug_scsi("sol dout [dsn %d itt 0x%x dlen %d sent %d]\n",
1689                         r2t->solicit_datasn - 1, ctask->itt, r2t->data_count,
1690                         r2t->sent);
1691         }
1692
1693         if (tcp_ctask->xmstate & XMSTATE_SOL_DATA) {
1694                 r2t = tcp_ctask->r2t;
1695                 dtask = &r2t->dtask;
1696
1697                 rc = iscsi_send_data(ctask, &r2t->sendbuf, &r2t->sg,
1698                                      &r2t->sent, &r2t->data_count,
1699                                      &dtask->digestbuf, &dtask->digest);
1700                 if (rc)
1701                         return rc;
1702                 tcp_ctask->xmstate &= ~XMSTATE_SOL_DATA;
1703
1704                 /*
1705                  * Done with this Data-Out. Next, check if we have
1706                  * to send another Data-Out for this R2T.
1707                  */
1708                 BUG_ON(r2t->data_length - r2t->sent < 0);
1709                 left = r2t->data_length - r2t->sent;
1710                 if (left) {
1711                         iscsi_solicit_data_cont(conn, ctask, r2t, left);
1712                         goto send_hdr;
1713                 }
1714
1715                 /*
1716                  * Done with this R2T. Check if there are more
1717                  * outstanding R2Ts ready to be processed.
1718                  */
1719                 spin_lock_bh(&session->lock);
1720                 tcp_ctask->r2t = NULL;
1721                 __kfifo_put(tcp_ctask->r2tpool.queue, (void*)&r2t,
1722                             sizeof(void*));
1723                 if (__kfifo_get(tcp_ctask->r2tqueue, (void*)&r2t,
1724                                 sizeof(void*))) {
1725                         tcp_ctask->r2t = r2t;
1726                         spin_unlock_bh(&session->lock);
1727                         goto send_hdr;
1728                 }
1729                 spin_unlock_bh(&session->lock);
1730         }
1731         return 0;
1732 }
1733
1734 /**
1735  * iscsi_tcp_ctask_xmit - xmit normal PDU task
1736  * @conn: iscsi connection
1737  * @ctask: iscsi command task
1738  *
1739  * Notes:
1740  *      The function can return -EAGAIN in which case caller must
1741  *      call it again later, or recover. '0' return code means successful
1742  *      xmit.
1743  *      The function is devided to logical helpers (above) for the different
1744  *      xmit stages.
1745  *
1746  *iscsi_send_cmd_hdr()
1747  *      XMSTATE_CMD_HDR_INIT - prepare Header and Data buffers Calculate
1748  *                             Header Digest
1749  *      XMSTATE_CMD_HDR_XMIT - Transmit header in progress
1750  *
1751  *iscsi_send_padding
1752  *      XMSTATE_W_PAD        - Prepare and send pading
1753  *      XMSTATE_W_RESEND_PAD - retry send pading
1754  *
1755  *iscsi_send_digest
1756  *      XMSTATE_W_RESEND_DATA_DIGEST - Finalize and send Data Digest
1757  *      XMSTATE_W_RESEND_DATA_DIGEST - retry sending digest
1758  *
1759  *iscsi_send_unsol_hdr
1760  *      XMSTATE_UNS_INIT     - prepare un-solicit data header and digest
1761  *      XMSTATE_UNS_HDR      - send un-solicit header
1762  *
1763  *iscsi_send_unsol_pdu
1764  *      XMSTATE_UNS_DATA     - send un-solicit data in progress
1765  *
1766  *iscsi_send_sol_pdu
1767  *      XMSTATE_SOL_HDR_INIT - solicit data header and digest initialize
1768  *      XMSTATE_SOL_HDR      - send solicit header
1769  *      XMSTATE_SOL_DATA     - send solicit data
1770  *
1771  *iscsi_tcp_ctask_xmit
1772  *      XMSTATE_IMM_DATA     - xmit managment data (??)
1773  **/
1774 static int
1775 iscsi_tcp_ctask_xmit(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
1776 {
1777         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1778         int rc = 0;
1779
1780         debug_scsi("ctask deq [cid %d xmstate %x itt 0x%x]\n",
1781                 conn->id, tcp_ctask->xmstate, ctask->itt);
1782
1783         rc = iscsi_send_cmd_hdr(conn, ctask);
1784         if (rc)
1785                 return rc;
1786         if (ctask->sc->sc_data_direction != DMA_TO_DEVICE)
1787                 return 0;
1788
1789         if (tcp_ctask->xmstate & XMSTATE_IMM_DATA) {
1790                 rc = iscsi_send_data(ctask, &tcp_ctask->sendbuf, &tcp_ctask->sg,
1791                                      &tcp_ctask->sent, &ctask->imm_count,
1792                                      &tcp_ctask->immbuf, &tcp_ctask->immdigest);
1793                 if (rc)
1794                         return rc;
1795                 tcp_ctask->xmstate &= ~XMSTATE_IMM_DATA;
1796         }
1797
1798         rc = iscsi_send_unsol_pdu(conn, ctask);
1799         if (rc)
1800                 return rc;
1801
1802         rc = iscsi_send_sol_pdu(conn, ctask);
1803         if (rc)
1804                 return rc;
1805
1806         return rc;
1807 }
1808
1809 static struct iscsi_cls_conn *
1810 iscsi_tcp_conn_create(struct iscsi_cls_session *cls_session, uint32_t conn_idx)
1811 {
1812         struct iscsi_conn *conn;
1813         struct iscsi_cls_conn *cls_conn;
1814         struct iscsi_tcp_conn *tcp_conn;
1815
1816         cls_conn = iscsi_conn_setup(cls_session, conn_idx);
1817         if (!cls_conn)
1818                 return NULL;
1819         conn = cls_conn->dd_data;
1820         /*
1821          * due to strange issues with iser these are not set
1822          * in iscsi_conn_setup
1823          */
1824         conn->max_recv_dlength = ISCSI_DEF_MAX_RECV_SEG_LEN;
1825
1826         tcp_conn = kzalloc(sizeof(*tcp_conn), GFP_KERNEL);
1827         if (!tcp_conn)
1828                 goto tcp_conn_alloc_fail;
1829
1830         conn->dd_data = tcp_conn;
1831         tcp_conn->iscsi_conn = conn;
1832         tcp_conn->in_progress = IN_PROGRESS_WAIT_HEADER;
1833         /* initial operational parameters */
1834         tcp_conn->hdr_size = sizeof(struct iscsi_hdr);
1835
1836         tcp_conn->tx_hash.tfm = crypto_alloc_hash("crc32c", 0,
1837                                                   CRYPTO_ALG_ASYNC);
1838         tcp_conn->tx_hash.flags = 0;
1839         if (IS_ERR(tcp_conn->tx_hash.tfm)) {
1840                 printk(KERN_ERR "Could not create connection due to crc32c "
1841                        "loading error %ld. Make sure the crc32c module is "
1842                        "built as a module or into the kernel\n",
1843                         PTR_ERR(tcp_conn->tx_hash.tfm));
1844                 goto free_tcp_conn;
1845         }
1846
1847         tcp_conn->rx_hash.tfm = crypto_alloc_hash("crc32c", 0,
1848                                                   CRYPTO_ALG_ASYNC);
1849         tcp_conn->rx_hash.flags = 0;
1850         if (IS_ERR(tcp_conn->rx_hash.tfm)) {
1851                 printk(KERN_ERR "Could not create connection due to crc32c "
1852                        "loading error %ld. Make sure the crc32c module is "
1853                        "built as a module or into the kernel\n",
1854                         PTR_ERR(tcp_conn->rx_hash.tfm));
1855                 goto free_tx_tfm;
1856         }
1857
1858         return cls_conn;
1859
1860 free_tx_tfm:
1861         crypto_free_hash(tcp_conn->tx_hash.tfm);
1862 free_tcp_conn:
1863         kfree(tcp_conn);
1864 tcp_conn_alloc_fail:
1865         iscsi_conn_teardown(cls_conn);
1866         return NULL;
1867 }
1868
1869 static void
1870 iscsi_tcp_release_conn(struct iscsi_conn *conn)
1871 {
1872         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1873
1874         if (!tcp_conn->sock)
1875                 return;
1876
1877         sock_hold(tcp_conn->sock->sk);
1878         iscsi_conn_restore_callbacks(tcp_conn);
1879         sock_put(tcp_conn->sock->sk);
1880
1881         sock_release(tcp_conn->sock);
1882         tcp_conn->sock = NULL;
1883         conn->recv_lock = NULL;
1884 }
1885
1886 static void
1887 iscsi_tcp_conn_destroy(struct iscsi_cls_conn *cls_conn)
1888 {
1889         struct iscsi_conn *conn = cls_conn->dd_data;
1890         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1891
1892         iscsi_tcp_release_conn(conn);
1893         iscsi_conn_teardown(cls_conn);
1894
1895         if (tcp_conn->tx_hash.tfm)
1896                 crypto_free_hash(tcp_conn->tx_hash.tfm);
1897         if (tcp_conn->rx_hash.tfm)
1898                 crypto_free_hash(tcp_conn->rx_hash.tfm);
1899
1900         kfree(tcp_conn);
1901 }
1902
1903 static void
1904 iscsi_tcp_conn_stop(struct iscsi_cls_conn *cls_conn, int flag)
1905 {
1906         struct iscsi_conn *conn = cls_conn->dd_data;
1907         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1908
1909         iscsi_conn_stop(cls_conn, flag);
1910         iscsi_tcp_release_conn(conn);
1911         tcp_conn->hdr_size = sizeof(struct iscsi_hdr);
1912 }
1913
1914 static int
1915 iscsi_tcp_conn_bind(struct iscsi_cls_session *cls_session,
1916                     struct iscsi_cls_conn *cls_conn, uint64_t transport_eph,
1917                     int is_leading)
1918 {
1919         struct iscsi_conn *conn = cls_conn->dd_data;
1920         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1921         struct sock *sk;
1922         struct socket *sock;
1923         int err;
1924
1925         /* lookup for existing socket */
1926         sock = sockfd_lookup((int)transport_eph, &err);
1927         if (!sock) {
1928                 printk(KERN_ERR "iscsi_tcp: sockfd_lookup failed %d\n", err);
1929                 return -EEXIST;
1930         }
1931
1932         err = iscsi_conn_bind(cls_session, cls_conn, is_leading);
1933         if (err)
1934                 return err;
1935
1936         /* bind iSCSI connection and socket */
1937         tcp_conn->sock = sock;
1938
1939         /* setup Socket parameters */
1940         sk = sock->sk;
1941         sk->sk_reuse = 1;
1942         sk->sk_sndtimeo = 15 * HZ; /* FIXME: make it configurable */
1943         sk->sk_allocation = GFP_ATOMIC;
1944
1945         /* FIXME: disable Nagle's algorithm */
1946
1947         /*
1948          * Intercept TCP callbacks for sendfile like receive
1949          * processing.
1950          */
1951         conn->recv_lock = &sk->sk_callback_lock;
1952         iscsi_conn_set_callbacks(conn);
1953         tcp_conn->sendpage = tcp_conn->sock->ops->sendpage;
1954         /*
1955          * set receive state machine into initial state
1956          */
1957         tcp_conn->in_progress = IN_PROGRESS_WAIT_HEADER;
1958
1959         return 0;
1960 }
1961
1962 /* called with host lock */
1963 static void
1964 iscsi_tcp_mgmt_init(struct iscsi_conn *conn, struct iscsi_mgmt_task *mtask)
1965 {
1966         struct iscsi_tcp_mgmt_task *tcp_mtask = mtask->dd_data;
1967         tcp_mtask->xmstate = XMSTATE_IMM_HDR_INIT;
1968 }
1969
1970 static int
1971 iscsi_r2tpool_alloc(struct iscsi_session *session)
1972 {
1973         int i;
1974         int cmd_i;
1975
1976         /*
1977          * initialize per-task: R2T pool and xmit queue
1978          */
1979         for (cmd_i = 0; cmd_i < session->cmds_max; cmd_i++) {
1980                 struct iscsi_cmd_task *ctask = session->cmds[cmd_i];
1981                 struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1982
1983                 /*
1984                  * pre-allocated x4 as much r2ts to handle race when
1985                  * target acks DataOut faster than we data_xmit() queues
1986                  * could replenish r2tqueue.
1987                  */
1988
1989                 /* R2T pool */
1990                 if (iscsi_pool_init(&tcp_ctask->r2tpool, session->max_r2t * 4,
1991                                     (void***)&tcp_ctask->r2ts,
1992                                     sizeof(struct iscsi_r2t_info))) {
1993                         goto r2t_alloc_fail;
1994                 }
1995
1996                 /* R2T xmit queue */
1997                 tcp_ctask->r2tqueue = kfifo_alloc(
1998                       session->max_r2t * 4 * sizeof(void*), GFP_KERNEL, NULL);
1999                 if (tcp_ctask->r2tqueue == ERR_PTR(-ENOMEM)) {
2000                         iscsi_pool_free(&tcp_ctask->r2tpool,
2001                                         (void**)tcp_ctask->r2ts);
2002                         goto r2t_alloc_fail;
2003                 }
2004         }
2005
2006         return 0;
2007
2008 r2t_alloc_fail:
2009         for (i = 0; i < cmd_i; i++) {
2010                 struct iscsi_cmd_task *ctask = session->cmds[i];
2011                 struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
2012
2013                 kfifo_free(tcp_ctask->r2tqueue);
2014                 iscsi_pool_free(&tcp_ctask->r2tpool,
2015                                 (void**)tcp_ctask->r2ts);
2016         }
2017         return -ENOMEM;
2018 }
2019
2020 static void
2021 iscsi_r2tpool_free(struct iscsi_session *session)
2022 {
2023         int i;
2024
2025         for (i = 0; i < session->cmds_max; i++) {
2026                 struct iscsi_cmd_task *ctask = session->cmds[i];
2027                 struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
2028
2029                 kfifo_free(tcp_ctask->r2tqueue);
2030                 iscsi_pool_free(&tcp_ctask->r2tpool,
2031                                 (void**)tcp_ctask->r2ts);
2032         }
2033 }
2034
2035 static int
2036 iscsi_conn_set_param(struct iscsi_cls_conn *cls_conn, enum iscsi_param param,
2037                      char *buf, int buflen)
2038 {
2039         struct iscsi_conn *conn = cls_conn->dd_data;
2040         struct iscsi_session *session = conn->session;
2041         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
2042         int value;
2043
2044         switch(param) {
2045         case ISCSI_PARAM_HDRDGST_EN:
2046                 iscsi_set_param(cls_conn, param, buf, buflen);
2047                 tcp_conn->hdr_size = sizeof(struct iscsi_hdr);
2048                 if (conn->hdrdgst_en)
2049                         tcp_conn->hdr_size += sizeof(__u32);
2050                 break;
2051         case ISCSI_PARAM_DATADGST_EN:
2052                 iscsi_set_param(cls_conn, param, buf, buflen);
2053                 tcp_conn->sendpage = conn->datadgst_en ?
2054                         sock_no_sendpage : tcp_conn->sock->ops->sendpage;
2055                 break;
2056         case ISCSI_PARAM_MAX_R2T:
2057                 sscanf(buf, "%d", &value);
2058                 if (session->max_r2t == roundup_pow_of_two(value))
2059                         break;
2060                 iscsi_r2tpool_free(session);
2061                 iscsi_set_param(cls_conn, param, buf, buflen);
2062                 if (session->max_r2t & (session->max_r2t - 1))
2063                         session->max_r2t = roundup_pow_of_two(session->max_r2t);
2064                 if (iscsi_r2tpool_alloc(session))
2065                         return -ENOMEM;
2066                 break;
2067         default:
2068                 return iscsi_set_param(cls_conn, param, buf, buflen);
2069         }
2070
2071         return 0;
2072 }
2073
2074 static int
2075 iscsi_tcp_conn_get_param(struct iscsi_cls_conn *cls_conn,
2076                          enum iscsi_param param, char *buf)
2077 {
2078         struct iscsi_conn *conn = cls_conn->dd_data;
2079         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
2080         struct inet_sock *inet;
2081         struct ipv6_pinfo *np;
2082         struct sock *sk;
2083         int len;
2084
2085         switch(param) {
2086         case ISCSI_PARAM_CONN_PORT:
2087                 if (!tcp_conn->sock)
2088                         return -EINVAL;
2089
2090                 inet = inet_sk(tcp_conn->sock->sk);
2091                 len = sprintf(buf, "%hu\n", be16_to_cpu(inet->dport));
2092                 break;
2093         case ISCSI_PARAM_CONN_ADDRESS:
2094                 if (!tcp_conn->sock)
2095                         return -EINVAL;
2096
2097                 sk = tcp_conn->sock->sk;
2098                 if (sk->sk_family == PF_INET) {
2099                         inet = inet_sk(sk);
2100                         len = sprintf(buf, NIPQUAD_FMT "\n",
2101                                       NIPQUAD(inet->daddr));
2102                 } else {
2103                         np = inet6_sk(sk);
2104                         len = sprintf(buf, NIP6_FMT "\n", NIP6(np->daddr));
2105                 }
2106                 break;
2107         default:
2108                 return iscsi_conn_get_param(cls_conn, param, buf);
2109         }
2110
2111         return len;
2112 }
2113
2114 static void
2115 iscsi_conn_get_stats(struct iscsi_cls_conn *cls_conn, struct iscsi_stats *stats)
2116 {
2117         struct iscsi_conn *conn = cls_conn->dd_data;
2118         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
2119
2120         stats->txdata_octets = conn->txdata_octets;
2121         stats->rxdata_octets = conn->rxdata_octets;
2122         stats->scsicmd_pdus = conn->scsicmd_pdus_cnt;
2123         stats->dataout_pdus = conn->dataout_pdus_cnt;
2124         stats->scsirsp_pdus = conn->scsirsp_pdus_cnt;
2125         stats->datain_pdus = conn->datain_pdus_cnt;
2126         stats->r2t_pdus = conn->r2t_pdus_cnt;
2127         stats->tmfcmd_pdus = conn->tmfcmd_pdus_cnt;
2128         stats->tmfrsp_pdus = conn->tmfrsp_pdus_cnt;
2129         stats->custom_length = 3;
2130         strcpy(stats->custom[0].desc, "tx_sendpage_failures");
2131         stats->custom[0].value = tcp_conn->sendpage_failures_cnt;
2132         strcpy(stats->custom[1].desc, "rx_discontiguous_hdr");
2133         stats->custom[1].value = tcp_conn->discontiguous_hdr_cnt;
2134         strcpy(stats->custom[2].desc, "eh_abort_cnt");
2135         stats->custom[2].value = conn->eh_abort_cnt;
2136 }
2137
2138 static struct iscsi_cls_session *
2139 iscsi_tcp_session_create(struct iscsi_transport *iscsit,
2140                          struct scsi_transport_template *scsit,
2141                          uint16_t cmds_max, uint16_t qdepth,
2142                          uint32_t initial_cmdsn, uint32_t *hostno)
2143 {
2144         struct iscsi_cls_session *cls_session;
2145         struct iscsi_session *session;
2146         uint32_t hn;
2147         int cmd_i;
2148
2149         cls_session = iscsi_session_setup(iscsit, scsit, cmds_max, qdepth,
2150                                          sizeof(struct iscsi_tcp_cmd_task),
2151                                          sizeof(struct iscsi_tcp_mgmt_task),
2152                                          initial_cmdsn, &hn);
2153         if (!cls_session)
2154                 return NULL;
2155         *hostno = hn;
2156
2157         session = class_to_transport_session(cls_session);
2158         for (cmd_i = 0; cmd_i < session->cmds_max; cmd_i++) {
2159                 struct iscsi_cmd_task *ctask = session->cmds[cmd_i];
2160                 struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
2161
2162                 ctask->hdr = &tcp_ctask->hdr;
2163         }
2164
2165         for (cmd_i = 0; cmd_i < session->mgmtpool_max; cmd_i++) {
2166                 struct iscsi_mgmt_task *mtask = session->mgmt_cmds[cmd_i];
2167                 struct iscsi_tcp_mgmt_task *tcp_mtask = mtask->dd_data;
2168
2169                 mtask->hdr = &tcp_mtask->hdr;
2170         }
2171
2172         if (iscsi_r2tpool_alloc(class_to_transport_session(cls_session)))
2173                 goto r2tpool_alloc_fail;
2174
2175         return cls_session;
2176
2177 r2tpool_alloc_fail:
2178         iscsi_session_teardown(cls_session);
2179         return NULL;
2180 }
2181
2182 static void iscsi_tcp_session_destroy(struct iscsi_cls_session *cls_session)
2183 {
2184         iscsi_r2tpool_free(class_to_transport_session(cls_session));
2185         iscsi_session_teardown(cls_session);
2186 }
2187
2188 static int iscsi_tcp_slave_configure(struct scsi_device *sdev)
2189 {
2190         blk_queue_dma_alignment(sdev->request_queue, 0);
2191         return 0;
2192 }
2193
2194 static struct scsi_host_template iscsi_sht = {
2195         .name                   = "iSCSI Initiator over TCP/IP",
2196         .queuecommand           = iscsi_queuecommand,
2197         .change_queue_depth     = iscsi_change_queue_depth,
2198         .can_queue              = ISCSI_DEF_XMIT_CMDS_MAX - 1,
2199         .sg_tablesize           = ISCSI_SG_TABLESIZE,
2200         .max_sectors            = 0xFFFF,
2201         .cmd_per_lun            = ISCSI_DEF_CMD_PER_LUN,
2202         .eh_abort_handler       = iscsi_eh_abort,
2203         .eh_host_reset_handler  = iscsi_eh_host_reset,
2204         .use_clustering         = DISABLE_CLUSTERING,
2205         .slave_configure        = iscsi_tcp_slave_configure,
2206         .proc_name              = "iscsi_tcp",
2207         .this_id                = -1,
2208 };
2209
2210 static struct iscsi_transport iscsi_tcp_transport = {
2211         .owner                  = THIS_MODULE,
2212         .name                   = "tcp",
2213         .caps                   = CAP_RECOVERY_L0 | CAP_MULTI_R2T | CAP_HDRDGST
2214                                   | CAP_DATADGST,
2215         .param_mask             = ISCSI_MAX_RECV_DLENGTH |
2216                                   ISCSI_MAX_XMIT_DLENGTH |
2217                                   ISCSI_HDRDGST_EN |
2218                                   ISCSI_DATADGST_EN |
2219                                   ISCSI_INITIAL_R2T_EN |
2220                                   ISCSI_MAX_R2T |
2221                                   ISCSI_IMM_DATA_EN |
2222                                   ISCSI_FIRST_BURST |
2223                                   ISCSI_MAX_BURST |
2224                                   ISCSI_PDU_INORDER_EN |
2225                                   ISCSI_DATASEQ_INORDER_EN |
2226                                   ISCSI_ERL |
2227                                   ISCSI_CONN_PORT |
2228                                   ISCSI_CONN_ADDRESS |
2229                                   ISCSI_EXP_STATSN |
2230                                   ISCSI_PERSISTENT_PORT |
2231                                   ISCSI_PERSISTENT_ADDRESS |
2232                                   ISCSI_TARGET_NAME | ISCSI_TPGT |
2233                                   ISCSI_USERNAME | ISCSI_PASSWORD |
2234                                   ISCSI_USERNAME_IN | ISCSI_PASSWORD_IN,
2235         .host_param_mask        = ISCSI_HOST_HWADDRESS |
2236                                   ISCSI_HOST_INITIATOR_NAME,
2237         .host_template          = &iscsi_sht,
2238         .conndata_size          = sizeof(struct iscsi_conn),
2239         .max_conn               = 1,
2240         .max_cmd_len            = ISCSI_TCP_MAX_CMD_LEN,
2241         /* session management */
2242         .create_session         = iscsi_tcp_session_create,
2243         .destroy_session        = iscsi_tcp_session_destroy,
2244         /* connection management */
2245         .create_conn            = iscsi_tcp_conn_create,
2246         .bind_conn              = iscsi_tcp_conn_bind,
2247         .destroy_conn           = iscsi_tcp_conn_destroy,
2248         .set_param              = iscsi_conn_set_param,
2249         .get_conn_param         = iscsi_tcp_conn_get_param,
2250         .get_session_param      = iscsi_session_get_param,
2251         .start_conn             = iscsi_conn_start,
2252         .stop_conn              = iscsi_tcp_conn_stop,
2253         /* iscsi host params */
2254         .get_host_param         = iscsi_host_get_param,
2255         .set_host_param         = iscsi_host_set_param,
2256         /* IO */
2257         .send_pdu               = iscsi_conn_send_pdu,
2258         .get_stats              = iscsi_conn_get_stats,
2259         .init_cmd_task          = iscsi_tcp_cmd_init,
2260         .init_mgmt_task         = iscsi_tcp_mgmt_init,
2261         .xmit_cmd_task          = iscsi_tcp_ctask_xmit,
2262         .xmit_mgmt_task         = iscsi_tcp_mtask_xmit,
2263         .cleanup_cmd_task       = iscsi_tcp_cleanup_ctask,
2264         /* recovery */
2265         .session_recovery_timedout = iscsi_session_recovery_timedout,
2266 };
2267
2268 static int __init
2269 iscsi_tcp_init(void)
2270 {
2271         if (iscsi_max_lun < 1) {
2272                 printk(KERN_ERR "iscsi_tcp: Invalid max_lun value of %u\n",
2273                        iscsi_max_lun);
2274                 return -EINVAL;
2275         }
2276         iscsi_tcp_transport.max_lun = iscsi_max_lun;
2277
2278         if (!iscsi_register_transport(&iscsi_tcp_transport))
2279                 return -ENODEV;
2280
2281         return 0;
2282 }
2283
2284 static void __exit
2285 iscsi_tcp_exit(void)
2286 {
2287         iscsi_unregister_transport(&iscsi_tcp_transport);
2288 }
2289
2290 module_init(iscsi_tcp_init);
2291 module_exit(iscsi_tcp_exit);