Log reduction
[android/platform/frameworks/opt/telephony.git] / src / java / com / android / internal / telephony / dataconnection / DcTracker.java
1 /*
2  * Copyright (C) 2006 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.android.internal.telephony.dataconnection;
18
19 import android.app.AlarmManager;
20 import android.app.PendingIntent;
21 import android.app.ProgressDialog;
22 import android.content.ActivityNotFoundException;
23 import android.content.BroadcastReceiver;
24 import android.content.ContentResolver;
25 import android.content.ContentValues;
26 import android.content.Context;
27 import android.content.Intent;
28 import android.content.IntentFilter;
29 import android.content.res.Resources;
30 import android.database.ContentObserver;
31 import android.database.Cursor;
32 import android.net.ConnectivityManager;
33 import android.net.LinkProperties;
34 import android.net.NetworkCapabilities;
35 import android.net.NetworkConfig;
36 import android.net.NetworkUtils;
37 import android.net.ProxyInfo;
38 import android.net.Uri;
39 import android.os.AsyncResult;
40 import android.os.Build;
41 import android.os.Bundle;
42 import android.os.Handler;
43 import android.os.Message;
44 import android.os.RegistrantList;
45 import android.os.ServiceManager;
46 import android.os.SystemClock;
47 import android.os.SystemProperties;
48 import android.os.UserHandle;
49 import android.provider.Settings;
50 import android.provider.Telephony;
51 import android.telephony.CellLocation;
52 import android.telephony.ServiceState;
53 import android.telephony.TelephonyManager;
54 import android.telephony.SubscriptionManager;
55 import android.telephony.cdma.CdmaCellLocation;
56 import android.telephony.gsm.GsmCellLocation;
57 import android.text.TextUtils;
58 import android.util.EventLog;
59 import android.view.WindowManager;
60 import android.telephony.Rlog;
61
62 import com.android.internal.telephony.cdma.CDMALTEPhone;
63 import com.android.internal.telephony.Phone;
64 import com.android.internal.telephony.PhoneBase;
65 import com.android.internal.telephony.DctConstants;
66 import com.android.internal.telephony.EventLogTags;
67 import com.android.internal.telephony.ITelephony;
68 import com.android.internal.telephony.TelephonyIntents;
69 import com.android.internal.telephony.gsm.GSMPhone;
70 import com.android.internal.telephony.PhoneConstants;
71 import com.android.internal.telephony.RILConstants;
72 import com.android.internal.telephony.uicc.IccRecords;
73 import com.android.internal.telephony.uicc.UiccController;
74 import com.android.internal.util.AsyncChannel;
75 import com.android.internal.util.ArrayUtils;
76
77 import java.io.FileDescriptor;
78 import java.io.PrintWriter;
79 import java.util.ArrayList;
80 import java.util.Arrays;
81 import java.util.concurrent.atomic.AtomicBoolean;
82 import java.util.Objects;
83 import java.lang.StringBuilder;
84
85 import com.android.internal.telephony.ServiceStateTracker;
86 /**
87  * {@hide}
88  */
89 public final class DcTracker extends DcTrackerBase {
90     protected final String LOG_TAG = "DCT";
91
92     /**
93      * List of messages that are waiting to be posted, when data call disconnect
94      * is complete
95      */
96     private ArrayList<Message> mDisconnectAllCompleteMsgList = new ArrayList<Message>();
97
98     private RegistrantList mAllDataDisconnectedRegistrants = new RegistrantList();
99
100     protected int mDisconnectPendingCount = 0;
101
102     /**
103      * Handles changes to the APN db.
104      */
105     private class ApnChangeObserver extends ContentObserver {
106         public ApnChangeObserver () {
107             super(mDataConnectionTracker);
108         }
109
110         @Override
111         public void onChange(boolean selfChange) {
112             sendMessage(obtainMessage(DctConstants.EVENT_APN_CHANGED));
113         }
114     }
115
116     //***** Instance Variables
117
118     private boolean mReregisterOnReconnectFailure = false;
119
120
121     //***** Constants
122
123     // Used by puppetmaster/*/radio_stress.py
124     private static final String PUPPET_MASTER_RADIO_STRESS_TEST = "gsm.defaultpdpcontext.active";
125
126     private static final int POLL_PDP_MILLIS = 5 * 1000;
127
128     private static final int PROVISIONING_SPINNER_TIMEOUT_MILLIS = 120 * 1000;
129
130     static final Uri PREFERAPN_NO_UPDATE_URI_USING_SUBID =
131                         Uri.parse("content://telephony/carriers/preferapn_no_update/subId/");
132     static final String APN_ID = "apn_id";
133
134     private boolean mCanSetPreferApn = false;
135
136     private AtomicBoolean mAttached = new AtomicBoolean(false);
137
138     /** Watches for changes to the APN db. */
139     private ApnChangeObserver mApnObserver;
140
141     private final String mProvisionActionName;
142     private BroadcastReceiver mProvisionBroadcastReceiver;
143     private ProgressDialog mProvisioningSpinner;
144
145     public boolean mImsRegistrationState = false;
146     private ApnContext mWaitCleanUpApnContext = null;
147     private boolean mDeregistrationAlarmState = false;
148     private PendingIntent mImsDeregistrationDelayIntent = null;
149
150     //***** Constructor
151     public DcTracker(PhoneBase p) {
152         super(p);
153         if (DBG) log("GsmDCT.constructor");
154
155         mDataConnectionTracker = this;
156         update();
157         mApnObserver = new ApnChangeObserver();
158         p.getContext().getContentResolver().registerContentObserver(
159                 Telephony.Carriers.CONTENT_URI, true, mApnObserver);
160
161         initApnContexts();
162
163         for (ApnContext apnContext : mApnContexts.values()) {
164             // Register the reconnect and restart actions.
165             IntentFilter filter = new IntentFilter();
166             filter.addAction(INTENT_RECONNECT_ALARM + '.' + apnContext.getApnType());
167             filter.addAction(INTENT_RESTART_TRYSETUP_ALARM + '.' + apnContext.getApnType());
168             mPhone.getContext().registerReceiver(mIntentReceiver, filter, null, mPhone);
169         }
170
171         // Add Emergency APN to APN setting list by default to support EPDN in sim absent cases
172         initEmergencyApnSetting();
173         addEmergencyApnSetting();
174
175         mProvisionActionName = "com.android.internal.telephony.PROVISION" + p.getPhoneId();
176     }
177
178     protected void registerForAllEvents() {
179         mPhone.mCi.registerForAvailable(this, DctConstants.EVENT_RADIO_AVAILABLE, null);
180         mPhone.mCi.registerForOffOrNotAvailable(this,
181                DctConstants.EVENT_RADIO_OFF_OR_NOT_AVAILABLE, null);
182         mPhone.mCi.registerForDataNetworkStateChanged(this,
183                DctConstants.EVENT_DATA_STATE_CHANGED, null);
184         // Note, this is fragile - the Phone is now presenting a merged picture
185         // of PS (volte) & CS and by diving into its internals you're just seeing
186         // the CS data.  This works well for the purposes this is currently used for
187         // but that may not always be the case.  Should probably be redesigned to
188         // accurately reflect what we're really interested in (registerForCSVoiceCallEnded).
189         mPhone.getCallTracker().registerForVoiceCallEnded (this,
190                DctConstants.EVENT_VOICE_CALL_ENDED, null);
191         mPhone.getCallTracker().registerForVoiceCallStarted (this,
192                DctConstants.EVENT_VOICE_CALL_STARTED, null);
193         mPhone.getServiceStateTracker().registerForDataConnectionAttached(this,
194                DctConstants.EVENT_DATA_CONNECTION_ATTACHED, null);
195         mPhone.getServiceStateTracker().registerForDataConnectionDetached(this,
196                DctConstants.EVENT_DATA_CONNECTION_DETACHED, null);
197         mPhone.getServiceStateTracker().registerForDataRoamingOn(this,
198                DctConstants.EVENT_ROAMING_ON, null);
199         mPhone.getServiceStateTracker().registerForDataRoamingOff(this,
200                DctConstants.EVENT_ROAMING_OFF, null);
201         mPhone.getServiceStateTracker().registerForPsRestrictedEnabled(this,
202                 DctConstants.EVENT_PS_RESTRICT_ENABLED, null);
203         mPhone.getServiceStateTracker().registerForPsRestrictedDisabled(this,
204                 DctConstants.EVENT_PS_RESTRICT_DISABLED, null);
205      //   SubscriptionManager.registerForDdsSwitch(this,
206      //          DctConstants.EVENT_CLEAN_UP_ALL_CONNECTIONS, null);
207         mPhone.getServiceStateTracker().registerForDataRegStateOrRatChanged(this,
208                 DctConstants.EVENT_DATA_RAT_CHANGED, null);
209     }
210     @Override
211     public void dispose() {
212         if (DBG) log("DcTracker.dispose");
213
214         if (mProvisionBroadcastReceiver != null) {
215             mPhone.getContext().unregisterReceiver(mProvisionBroadcastReceiver);
216             mProvisionBroadcastReceiver = null;
217         }
218         if (mProvisioningSpinner != null) {
219             mProvisioningSpinner.dismiss();
220             mProvisioningSpinner = null;
221         }
222
223         cleanUpAllConnections(true, null);
224
225         super.dispose();
226
227         mPhone.getContext().getContentResolver().unregisterContentObserver(mApnObserver);
228         mApnContexts.clear();
229         mPrioritySortedApnContexts.clear();
230
231         destroyDataConnections();
232     }
233     protected void unregisterForAllEvents() {
234          //Unregister for all events
235         mPhone.mCi.unregisterForAvailable(this);
236         mPhone.mCi.unregisterForOffOrNotAvailable(this);
237         IccRecords r = mIccRecords.get();
238         if (r != null) {
239             r.unregisterForRecordsLoaded(this);
240             mIccRecords.set(null);
241         }
242         mPhone.mCi.unregisterForDataNetworkStateChanged(this);
243         mPhone.getCallTracker().unregisterForVoiceCallEnded(this);
244         mPhone.getCallTracker().unregisterForVoiceCallStarted(this);
245         mPhone.getServiceStateTracker().unregisterForDataConnectionAttached(this);
246         mPhone.getServiceStateTracker().unregisterForDataConnectionDetached(this);
247         mPhone.getServiceStateTracker().unregisterForDataRoamingOn(this);
248         mPhone.getServiceStateTracker().unregisterForDataRoamingOff(this);
249         mPhone.getServiceStateTracker().unregisterForPsRestrictedEnabled(this);
250         mPhone.getServiceStateTracker().unregisterForPsRestrictedDisabled(this);
251         //SubscriptionManager.unregisterForDdsSwitch(this);
252     }
253
254     @Override
255     public void incApnRefCount(String name) {
256         ApnContext apnContext = mApnContexts.get(name);
257         if (apnContext != null) {
258             apnContext.incRefCount();
259         }
260     }
261
262     @Override
263     public void decApnRefCount(String name) {
264         ApnContext apnContext = mApnContexts.get(name);
265         if (apnContext != null) {
266             apnContext.decRefCount();
267         }
268     }
269
270     @Override
271     public boolean isApnSupported(String name) {
272         if (name == null) {
273             loge("isApnSupported: name=null");
274             return false;
275         }
276         ApnContext apnContext = mApnContexts.get(name);
277         if (apnContext == null) {
278             loge("Request for unsupported mobile name: " + name);
279             return false;
280         }
281         return true;
282     }
283
284     @Override
285     public int getApnPriority(String name) {
286         ApnContext apnContext = mApnContexts.get(name);
287         if (apnContext == null) {
288             loge("Request for unsupported mobile name: " + name);
289         }
290         return apnContext.priority;
291     }
292
293     // Turn telephony radio on or off.
294     private void setRadio(boolean on) {
295         final ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone"));
296         try {
297             phone.setRadio(on);
298         } catch (Exception e) {
299             // Ignore.
300         }
301     }
302
303     // Class to handle Intent dispatched with user selects the "Sign-in to network"
304     // notification.
305     private class ProvisionNotificationBroadcastReceiver extends BroadcastReceiver {
306         private final String mNetworkOperator;
307         // Mobile provisioning URL.  Valid while provisioning notification is up.
308         // Set prior to notification being posted as URL contains ICCID which
309         // disappears when radio is off (which is the case when notification is up).
310         private final String mProvisionUrl;
311
312         public ProvisionNotificationBroadcastReceiver(String provisionUrl, String networkOperator) {
313             mNetworkOperator = networkOperator;
314             mProvisionUrl = provisionUrl;
315         }
316
317         private void setEnableFailFastMobileData(int enabled) {
318             sendMessage(obtainMessage(DctConstants.CMD_SET_ENABLE_FAIL_FAST_MOBILE_DATA, enabled, 0));
319         }
320
321         private void enableMobileProvisioning() {
322             final Message msg = obtainMessage(DctConstants.CMD_ENABLE_MOBILE_PROVISIONING);
323             msg.setData(Bundle.forPair(DctConstants.PROVISIONING_URL_KEY, mProvisionUrl));
324             sendMessage(msg);
325         }
326
327         @Override
328         public void onReceive(Context context, Intent intent) {
329             // Turning back on the radio can take time on the order of a minute, so show user a
330             // spinner so they know something is going on.
331             mProvisioningSpinner = new ProgressDialog(context);
332             mProvisioningSpinner.setTitle(mNetworkOperator);
333             mProvisioningSpinner.setMessage(
334                     // TODO: Don't borrow "Connecting..." i18n string; give Telephony a version.
335                     context.getText(com.android.internal.R.string.media_route_status_connecting));
336             mProvisioningSpinner.setIndeterminate(true);
337             mProvisioningSpinner.setCancelable(true);
338             // Allow non-Activity Service Context to create a View.
339             mProvisioningSpinner.getWindow().setType(
340                     WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
341             mProvisioningSpinner.show();
342             // After timeout, hide spinner so user can at least use their device.
343             // TODO: Indicate to user that it is taking an unusually long time to connect?
344             sendMessageDelayed(obtainMessage(DctConstants.CMD_CLEAR_PROVISIONING_SPINNER,
345                     mProvisioningSpinner), PROVISIONING_SPINNER_TIMEOUT_MILLIS);
346             // This code is almost identical to the old
347             // ConnectivityService.handleMobileProvisioningAction code.
348             setRadio(true);
349             setEnableFailFastMobileData(DctConstants.ENABLED);
350             enableMobileProvisioning();
351         }
352     }
353
354     @Override
355     public boolean isApnTypeActive(String type) {
356         ApnContext apnContext = mApnContexts.get(type);
357         if (apnContext == null) return false;
358
359         return (apnContext.getDcAc() != null);
360     }
361
362     @Override
363     public boolean isDataPossible(String apnType) {
364         ApnContext apnContext = mApnContexts.get(apnType);
365         if (apnContext == null) {
366             return false;
367         }
368         boolean apnContextIsEnabled = apnContext.isEnabled();
369         DctConstants.State apnContextState = apnContext.getState();
370         boolean apnTypePossible = !(apnContextIsEnabled &&
371                 (apnContextState == DctConstants.State.FAILED));
372         boolean isEmergencyApn = apnContext.getApnType().equals(PhoneConstants.APN_TYPE_EMERGENCY);
373         // Set the emergency APN availability status as TRUE irrespective of conditions checked in
374         // isDataAllowed() like IN_SERVICE, MOBILE DATA status etc.
375         boolean dataAllowed = isEmergencyApn || isDataAllowed();
376         boolean possible = dataAllowed && apnTypePossible;
377
378         if ((apnContext.getApnType().equals(PhoneConstants.APN_TYPE_DEFAULT)
379                     || apnContext.getApnType().equals(PhoneConstants.APN_TYPE_IA))
380                 && (mPhone.getServiceState().getRilDataRadioTechnology()
381                 == ServiceState.RIL_RADIO_TECHNOLOGY_IWLAN)) {
382             log("Default data call activation not possible in iwlan.");
383             possible = false;
384         }
385
386         if (VDBG) {
387             log(String.format("isDataPossible(%s): possible=%b isDataAllowed=%b " +
388                     "apnTypePossible=%b apnContextisEnabled=%b apnContextState()=%s",
389                     apnType, possible, dataAllowed, apnTypePossible,
390                     apnContextIsEnabled, apnContextState));
391         }
392         return possible;
393     }
394
395     @Override
396     protected void finalize() {
397         if(DBG) log("finalize");
398     }
399
400     private ApnContext addApnContext(String type, NetworkConfig networkConfig) {
401         ApnContext apnContext = new ApnContext(mPhone.getContext(), type, LOG_TAG, networkConfig,
402                 this);
403         mApnContexts.put(type, apnContext);
404         mPrioritySortedApnContexts.add(apnContext);
405         return apnContext;
406     }
407
408     protected void initApnContexts() {
409         log("initApnContexts: E");
410         // Load device network attributes from resources
411         String[] networkConfigStrings = mPhone.getContext().getResources().getStringArray(
412                 com.android.internal.R.array.networkAttributes);
413         for (String networkConfigString : networkConfigStrings) {
414             NetworkConfig networkConfig = new NetworkConfig(networkConfigString);
415             ApnContext apnContext = null;
416
417             switch (networkConfig.type) {
418             case ConnectivityManager.TYPE_MOBILE:
419                 apnContext = addApnContext(PhoneConstants.APN_TYPE_DEFAULT, networkConfig);
420                 break;
421             case ConnectivityManager.TYPE_MOBILE_MMS:
422                 apnContext = addApnContext(PhoneConstants.APN_TYPE_MMS, networkConfig);
423                 break;
424             case ConnectivityManager.TYPE_MOBILE_SUPL:
425                 apnContext = addApnContext(PhoneConstants.APN_TYPE_SUPL, networkConfig);
426                 break;
427             case ConnectivityManager.TYPE_MOBILE_DUN:
428                 apnContext = addApnContext(PhoneConstants.APN_TYPE_DUN, networkConfig);
429                 break;
430             case ConnectivityManager.TYPE_MOBILE_HIPRI:
431                 apnContext = addApnContext(PhoneConstants.APN_TYPE_HIPRI, networkConfig);
432                 break;
433             case ConnectivityManager.TYPE_MOBILE_FOTA:
434                 apnContext = addApnContext(PhoneConstants.APN_TYPE_FOTA, networkConfig);
435                 break;
436             case ConnectivityManager.TYPE_MOBILE_IMS:
437                 apnContext = addApnContext(PhoneConstants.APN_TYPE_IMS, networkConfig);
438                 break;
439             case ConnectivityManager.TYPE_MOBILE_CBS:
440                 apnContext = addApnContext(PhoneConstants.APN_TYPE_CBS, networkConfig);
441                 break;
442             case ConnectivityManager.TYPE_MOBILE_IA:
443                 apnContext = addApnContext(PhoneConstants.APN_TYPE_IA, networkConfig);
444                 break;
445             case ConnectivityManager.TYPE_MOBILE_EMERGENCY:
446                 apnContext = addApnContext(PhoneConstants.APN_TYPE_EMERGENCY, networkConfig);
447                 break;
448             default:
449                 log("initApnContexts: skipping unknown type=" + networkConfig.type);
450                 continue;
451             }
452             log("initApnContexts: apnContext=" + apnContext);
453         }
454         log("initApnContexts: X mApnContexts=" + mApnContexts);
455     }
456
457     @Override
458     public LinkProperties getLinkProperties(String apnType) {
459         ApnContext apnContext = mApnContexts.get(apnType);
460         if (apnContext != null) {
461             DcAsyncChannel dcac = apnContext.getDcAc();
462             if (dcac != null) {
463                 if (DBG) log("return link properites for " + apnType);
464                 return dcac.getLinkPropertiesSync();
465             }
466         }
467         if (DBG) log("return new LinkProperties");
468         return new LinkProperties();
469     }
470
471     @Override
472     public NetworkCapabilities getNetworkCapabilities(String apnType) {
473         ApnContext apnContext = mApnContexts.get(apnType);
474         if (apnContext!=null) {
475             DcAsyncChannel dataConnectionAc = apnContext.getDcAc();
476             if (dataConnectionAc != null) {
477                 if (DBG) {
478                     log("get active pdp is not null, return NetworkCapabilities for " + apnType);
479                 }
480                 return dataConnectionAc.getNetworkCapabilitiesSync();
481             }
482         }
483         if (DBG) log("return new NetworkCapabilities");
484         return new NetworkCapabilities();
485     }
486
487     @Override
488     // Return all active apn types
489     public String[] getActiveApnTypes() {
490         if (DBG) log("get all active apn types");
491         ArrayList<String> result = new ArrayList<String>();
492
493         for (ApnContext apnContext : mApnContexts.values()) {
494             if (mAttached.get() && apnContext.isReady()) {
495                 result.add(apnContext.getApnType());
496             }
497         }
498
499         return result.toArray(new String[0]);
500     }
501
502     @Override
503     // Return active apn of specific apn type
504     public String getActiveApnString(String apnType) {
505         if (VDBG) log( "get active apn string for type:" + apnType);
506         ApnContext apnContext = mApnContexts.get(apnType);
507         if (apnContext != null) {
508             ApnSetting apnSetting = apnContext.getApnSetting();
509             if (apnSetting != null) {
510                 return apnSetting.apn;
511             }
512         }
513         return null;
514     }
515
516     @Override
517     public boolean isApnTypeEnabled(String apnType) {
518         ApnContext apnContext = mApnContexts.get(apnType);
519         if (apnContext == null) {
520             return false;
521         }
522         return apnContext.isEnabled();
523     }
524
525     @Override
526     protected void setState(DctConstants.State s) {
527         if (DBG) log("setState should not be used in GSM" + s);
528     }
529
530     // Return state of specific apn type
531     @Override
532     public DctConstants.State getState(String apnType) {
533         ApnContext apnContext = mApnContexts.get(apnType);
534         if (apnContext != null) {
535             return apnContext.getState();
536         }
537         return DctConstants.State.FAILED;
538     }
539
540     // Return if apn type is a provisioning apn.
541     @Override
542     protected boolean isProvisioningApn(String apnType) {
543         ApnContext apnContext = mApnContexts.get(apnType);
544         if (apnContext != null) {
545             return apnContext.isProvisioningApn();
546         }
547         return false;
548     }
549
550     // Return state of overall
551     @Override
552     public DctConstants.State getOverallState() {
553         boolean isConnecting = false;
554         boolean isFailed = true; // All enabled Apns should be FAILED.
555         boolean isAnyEnabled = false;
556
557         for (ApnContext apnContext : mApnContexts.values()) {
558             if (apnContext.isEnabled()) {
559                 isAnyEnabled = true;
560                 switch (apnContext.getState()) {
561                 case CONNECTED:
562                 case DISCONNECTING:
563                     if (DBG) log("overall state is CONNECTED");
564                     return DctConstants.State.CONNECTED;
565                 case RETRYING:
566                 case CONNECTING:
567                     isConnecting = true;
568                     isFailed = false;
569                     break;
570                 case IDLE:
571                 case SCANNING:
572                     isFailed = false;
573                     break;
574                 default:
575                     isAnyEnabled = true;
576                     break;
577                 }
578             }
579         }
580
581         if (!isAnyEnabled) { // Nothing enabled. return IDLE.
582             if (DBG) log( "overall state is IDLE");
583             return DctConstants.State.IDLE;
584         }
585
586         if (isConnecting) {
587             if (DBG) log( "overall state is CONNECTING");
588             return DctConstants.State.CONNECTING;
589         } else if (!isFailed) {
590             if (DBG) log( "overall state is IDLE");
591             return DctConstants.State.IDLE;
592         } else {
593             if (DBG) log( "overall state is FAILED");
594             return DctConstants.State.FAILED;
595         }
596     }
597
598     @Override
599     protected boolean isApnTypeAvailable(String type) {
600         if (type.equals(PhoneConstants.APN_TYPE_DUN) && fetchDunApn() != null) {
601             return true;
602         }
603
604         if (mAllApnSettings != null) {
605             for (ApnSetting apn : mAllApnSettings) {
606                 if (apn.canHandleType(type)) {
607                     return true;
608                 }
609             }
610         }
611         return false;
612     }
613
614     /**
615      * Report on whether data connectivity is enabled for any APN.
616      * @return {@code false} if data connectivity has been explicitly disabled,
617      * {@code true} otherwise.
618      */
619     @Override
620     public boolean getAnyDataEnabled() {
621         synchronized (mDataEnabledLock) {
622             if (!(mInternalDataEnabled && mUserDataEnabled && sPolicyDataEnabled)) return false;
623             for (ApnContext apnContext : mApnContexts.values()) {
624                 // Make sure we don't have a context that is going down
625                 // and is explicitly disabled.
626                 if (isDataAllowed(apnContext)) {
627                     return true;
628                 }
629             }
630             return false;
631         }
632     }
633
634     public boolean getAnyDataEnabled(boolean checkUserDataEnabled) {
635         synchronized (mDataEnabledLock) {
636             if (!(mInternalDataEnabled && (!checkUserDataEnabled || mUserDataEnabled)
637                         && (!checkUserDataEnabled || sPolicyDataEnabled)))
638                 return false;
639
640             for (ApnContext apnContext : mApnContexts.values()) {
641                 // Make sure we dont have a context that going down
642                 // and is explicitly disabled.
643                 if (isDataAllowed(apnContext)) {
644                     return true;
645                 }
646             }
647             return false;
648         }
649     }
650
651     private boolean isDataAllowed(ApnContext apnContext) {
652         //If RAT is iwlan then dont allow default/IA PDP at all.
653         //Rest of APN types can be evaluated for remaining conditions.
654         if ((apnContext.getApnType().equals(PhoneConstants.APN_TYPE_DEFAULT)
655                     || apnContext.getApnType().equals(PhoneConstants.APN_TYPE_IA))
656                 && (mPhone.getServiceState().getRilDataRadioTechnology()
657                 == ServiceState.RIL_RADIO_TECHNOLOGY_IWLAN)) {
658             log("Default data call activation not allowed in iwlan.");
659             return false;
660         } else {
661             return apnContext.isReady() && isDataAllowed();
662         }
663     }
664
665     //****** Called from ServiceStateTracker
666     /**
667      * Invoked when ServiceStateTracker observes a transition from GPRS
668      * attach to detach.
669      */
670     protected void onDataConnectionDetached() {
671         /*
672          * We presently believe it is unnecessary to tear down the PDP context
673          * when GPRS detaches, but we should stop the network polling.
674          */
675         if (DBG) log ("onDataConnectionDetached: stop polling and notify detached");
676         stopNetStatPoll();
677         stopDataStallAlarm();
678         notifyDataConnection(Phone.REASON_DATA_DETACHED);
679         mAttached.set(false);
680     }
681
682     private void onDataConnectionAttached() {
683         if (DBG) log("onDataConnectionAttached");
684         mAttached.set(true);
685         if (getOverallState() == DctConstants.State.CONNECTED) {
686             if (DBG) log("onDataConnectionAttached: start polling notify attached");
687             startNetStatPoll();
688             startDataStallAlarm(DATA_STALL_NOT_SUSPECTED);
689             notifyDataConnection(Phone.REASON_DATA_ATTACHED);
690         } else {
691             // update APN availability so that APN can be enabled.
692             notifyOffApnsOfAvailability(Phone.REASON_DATA_ATTACHED);
693         }
694         if (mAutoAttachOnCreationConfig) {
695             mAutoAttachOnCreation = true;
696         }
697         setupDataOnConnectableApns(Phone.REASON_DATA_ATTACHED);
698     }
699
700     @Override
701     protected boolean isDataAllowed() {
702         final boolean internalDataEnabled;
703         synchronized (mDataEnabledLock) {
704             internalDataEnabled = mInternalDataEnabled;
705         }
706
707         boolean attachedState = mAttached.get();
708         boolean desiredPowerState = mPhone.getServiceStateTracker().getDesiredPowerState();
709         int radioTech = mPhone.getServiceState().getRilDataRadioTechnology();
710         if (radioTech == ServiceState.RIL_RADIO_TECHNOLOGY_IWLAN) {
711             desiredPowerState = true;
712         }
713
714         IccRecords r = mIccRecords.get();
715         boolean recordsLoaded = false;
716         if (r != null) {
717             recordsLoaded = r.getRecordsLoaded();
718             if (DBG && !recordsLoaded) log("isDataAllowed getRecordsLoaded=" + recordsLoaded);
719         }
720
721         //FIXME always attach
722         boolean psRestricted = mIsPsRestricted;
723         int phoneNum = TelephonyManager.getDefault().getPhoneCount();
724         if (phoneNum > 1) {
725             attachedState = true;
726             psRestricted = false;
727         }
728         int dataSub = SubscriptionManager.getDefaultDataSubId();
729         boolean defaultDataSelected = SubscriptionManager.isValidSubscriptionId(dataSub);
730         PhoneConstants.State state = PhoneConstants.State.IDLE;
731         // Note this is explicitly not using mPhone.getState.  See b/19090488.
732         // mPhone.getState reports the merge of CS and PS (volte) voice call state
733         // but we only care about CS calls here for data/voice concurrency issues.
734         // Calling getCallTracker currently gives you just the CS side where the
735         // ImsCallTracker is held internally where applicable.
736         // This should be redesigned to ask explicitly what we want:
737         // voiceCallStateAllowDataCall, or dataCallAllowed or something similar.
738         if (mPhone.getCallTracker() != null) {
739             state = mPhone.getCallTracker().getState();
740         }
741         boolean allowed =
742                     (attachedState || mAutoAttachOnCreation) &&
743                     recordsLoaded &&
744                     (state == PhoneConstants.State.IDLE ||
745                      mPhone.getServiceStateTracker().isConcurrentVoiceAndDataAllowed()) &&
746                     internalDataEnabled &&
747                     defaultDataSelected &&
748                     (!mPhone.getServiceState().getDataRoaming() || getDataOnRoamingEnabled()) &&
749                     //!mIsPsRestricted &&
750                     !psRestricted &&
751                     desiredPowerState;
752         if (!allowed && DBG) {
753             String reason = "";
754             if (!(attachedState || mAutoAttachOnCreation)) {
755                 reason += " - Attached= " + attachedState;
756             }
757             if (!recordsLoaded) reason += " - SIM not loaded";
758             if (state != PhoneConstants.State.IDLE &&
759                     !mPhone.getServiceStateTracker().isConcurrentVoiceAndDataAllowed()) {
760                 reason += " - PhoneState= " + state;
761                 reason += " - Concurrent voice and data not allowed";
762             }
763             if (!internalDataEnabled) reason += " - mInternalDataEnabled= false";
764             if (!defaultDataSelected) reason += " - defaultDataSelected= false";
765             if (mPhone.getServiceState().getDataRoaming() && !getDataOnRoamingEnabled()) {
766                 reason += " - Roaming and data roaming not enabled";
767             }
768             if (mIsPsRestricted) reason += " - mIsPsRestricted= true";
769             if (!desiredPowerState) reason += " - desiredPowerState= false";
770             if (DBG) log("isDataAllowed: not allowed due to" + reason);
771         }
772         return allowed;
773     }
774
775     // arg for setupDataOnConnectableApns
776     private enum RetryFailures {
777         // retry failed networks always (the old default)
778         ALWAYS,
779         // retry only when a substantial change has occured.  Either:
780         // 1) we were restricted by voice/data concurrency and aren't anymore
781         // 2) our apn list has change
782         ONLY_ON_CHANGE
783     };
784
785     private void setupDataOnConnectableApns(String reason) {
786         setupDataOnConnectableApns(reason, RetryFailures.ALWAYS);
787     }
788
789     private void setupDataOnConnectableApns(String reason, RetryFailures retryFailures) {
790         if (DBG) log("setupDataOnConnectableApns: " + reason);
791
792         for (ApnContext apnContext : mPrioritySortedApnContexts) {
793             ArrayList<ApnSetting> waitingApns = null;
794
795             if (DBG) log("setupDataOnConnectableApns: apnContext " + apnContext);
796             if (apnContext.getState() == DctConstants.State.FAILED
797                     || apnContext.getState() == DctConstants.State.RETRYING) {
798                 if (retryFailures == RetryFailures.ALWAYS) {
799                     apnContext.setState(DctConstants.State.IDLE);
800                 } else if (apnContext.isConcurrentVoiceAndDataAllowed() == false &&
801                          mPhone.getServiceStateTracker().isConcurrentVoiceAndDataAllowed()) {
802                     // RetryFailures.ONLY_ON_CHANGE - check if voice concurrency has changed
803                     apnContext.setState(DctConstants.State.IDLE);
804                 } else {
805                     // RetryFailures.ONLY_ON_CHANGE - check if the apns have changed
806                     int radioTech = mPhone.getServiceState().getRilDataRadioTechnology();
807                     ArrayList<ApnSetting> originalApns = apnContext.getOriginalWaitingApns();
808                     if (originalApns != null && originalApns.isEmpty() == false) {
809                         waitingApns = buildWaitingApns(apnContext.getApnType(), radioTech);
810                         if (originalApns.size() != waitingApns.size() ||
811                                 originalApns.containsAll(waitingApns) == false) {
812                             apnContext.setState(DctConstants.State.IDLE);
813                         }
814                     }
815                 }
816             }
817             if (apnContext.isConnectable()) {
818                 log("setupDataOnConnectableApns: isConnectable() call trySetupData");
819                 apnContext.setReason(reason);
820                 trySetupData(apnContext, waitingApns);
821             }
822         }
823     }
824
825     private boolean trySetupData(ApnContext apnContext) {
826         return trySetupData(apnContext, null);
827     }
828
829     private boolean trySetupData(ApnContext apnContext, ArrayList<ApnSetting> waitingApns) {
830         if (DBG) {
831             log("trySetupData for type:" + apnContext.getApnType() +
832                     " due to " + apnContext.getReason() + " apnContext=" + apnContext);
833             log("trySetupData with mIsPsRestricted=" + mIsPsRestricted);
834         }
835
836         if (mPhone.getSimulatedRadioControl() != null) {
837             // Assume data is connected on the simulator
838             // FIXME  this can be improved
839             apnContext.setState(DctConstants.State.CONNECTED);
840             mPhone.notifyDataConnection(apnContext.getReason(), apnContext.getApnType());
841
842             log("trySetupData: X We're on the simulator; assuming connected retValue=true");
843             return true;
844         }
845
846         // Allow SETUP_DATA request for E-APN to be completed during emergency call
847         // and MOBILE DATA On/Off cases as well.
848         boolean isEmergencyApn = apnContext.getApnType().equals(PhoneConstants.APN_TYPE_EMERGENCY);
849         final ServiceStateTracker sst = mPhone.getServiceStateTracker();
850         boolean desiredPowerState = sst.getDesiredPowerState();
851         boolean checkUserDataEnabled =
852                     !(apnContext.getApnType().equals(PhoneConstants.APN_TYPE_IMS));
853
854         if (apnContext.isConnectable() && (isEmergencyApn ||
855                 (isDataAllowed(apnContext) &&
856                 getAnyDataEnabled(checkUserDataEnabled) && !isEmergency()))) {
857             if (apnContext.getState() == DctConstants.State.FAILED) {
858                 if (DBG) log("trySetupData: make a FAILED ApnContext IDLE so its reusable");
859                 apnContext.setState(DctConstants.State.IDLE);
860             }
861             int radioTech = mPhone.getServiceState().getRilDataRadioTechnology();
862             apnContext.setConcurrentVoiceAndDataAllowed(sst.isConcurrentVoiceAndDataAllowed());
863             if (apnContext.getState() == DctConstants.State.IDLE) {
864                 if (waitingApns == null) {
865                     waitingApns = buildWaitingApns(apnContext.getApnType(), radioTech);
866                 }
867                 if (waitingApns.isEmpty()) {
868                     notifyNoData(DcFailCause.MISSING_UNKNOWN_APN, apnContext);
869                     notifyOffApnsOfAvailability(apnContext.getReason());
870                     if (DBG) log("trySetupData: X No APN found retValue=false");
871                     return false;
872                 } else {
873                     apnContext.setWaitingApns(waitingApns);
874                     if (DBG) {
875                         log ("trySetupData: Create from mAllApnSettings : "
876                                     + apnListToString(mAllApnSettings));
877                     }
878                 }
879             }
880
881             if (DBG) {
882                 log("trySetupData: call setupData, waitingApns : "
883                         + apnListToString(apnContext.getWaitingApns()));
884             }
885             boolean retValue = setupData(apnContext, radioTech);
886             notifyOffApnsOfAvailability(apnContext.getReason());
887
888             if (DBG) log("trySetupData: X retValue=" + retValue);
889             return retValue;
890         } else {
891             if (!apnContext.getApnType().equals(PhoneConstants.APN_TYPE_DEFAULT)
892                     && apnContext.isConnectable()) {
893                 mPhone.notifyDataConnectionFailed(apnContext.getReason(), apnContext.getApnType());
894             }
895             notifyOffApnsOfAvailability(apnContext.getReason());
896             if (DBG) log ("trySetupData: X apnContext not 'ready' retValue=false");
897             return false;
898         }
899     }
900
901     @Override
902     // Disabled apn's still need avail/unavail notificiations - send them out
903     protected void notifyOffApnsOfAvailability(String reason) {
904         for (ApnContext apnContext : mApnContexts.values()) {
905             if (!mAttached.get() || !apnContext.isReady()) {
906                 if (VDBG) log("notifyOffApnOfAvailability type:" + apnContext.getApnType());
907                 mPhone.notifyDataConnection(reason != null ? reason : apnContext.getReason(),
908                                             apnContext.getApnType(),
909                                             PhoneConstants.DataState.DISCONNECTED);
910             } else {
911                 if (VDBG) {
912                     log("notifyOffApnsOfAvailability skipped apn due to attached && isReady " +
913                             apnContext.toString());
914                 }
915             }
916         }
917     }
918
919     /**
920      * If tearDown is true, this only tears down a CONNECTED session. Presently,
921      * there is no mechanism for abandoning an CONNECTING session,
922      * but would likely involve cancelling pending async requests or
923      * setting a flag or new state to ignore them when they came in
924      * @param tearDown true if the underlying DataConnection should be
925      * disconnected.
926      * @param reason reason for the clean up.
927      * @return boolean - true if we did cleanup any connections, false if they
928      *                   were already all disconnected.
929      */
930     protected boolean cleanUpAllConnections(boolean tearDown, String reason) {
931         if (DBG) log("cleanUpAllConnections: tearDown=" + tearDown + " reason=" + reason);
932         boolean didDisconnect = false;
933         boolean specificdisable = false;
934
935         if (!TextUtils.isEmpty(reason)) {
936             specificdisable = reason.equals(Phone.REASON_DATA_SPECIFIC_DISABLED);
937         }
938
939         for (ApnContext apnContext : mApnContexts.values()) {
940             if (apnContext.isDisconnected() == false) didDisconnect = true;
941             if (specificdisable) {
942                 if (!apnContext.getApnType().equals(PhoneConstants.APN_TYPE_IMS)) {
943                     if (DBG) log("ApnConextType: " + apnContext.getApnType());
944                     apnContext.setReason(reason);
945                     cleanUpConnection(tearDown, apnContext);
946                 }
947             } else {
948                 // TODO - only do cleanup if not disconnected
949                 apnContext.setReason(reason);
950                 cleanUpConnection(tearDown, apnContext);
951             }
952         }
953
954         stopNetStatPoll();
955         stopDataStallAlarm();
956
957         // TODO: Do we need mRequestedApnType?
958         mRequestedApnType = PhoneConstants.APN_TYPE_DEFAULT;
959
960         log("cleanUpConnection: mDisconnectPendingCount = " + mDisconnectPendingCount);
961         if (tearDown && mDisconnectPendingCount == 0) {
962             notifyDataDisconnectComplete();
963             notifyAllDataDisconnected();
964         }
965
966         return didDisconnect;
967     }
968
969     /**
970      * Cleanup all connections.
971      *
972      * TODO: Cleanup only a specified connection passed as a parameter.
973      *       Also, make sure when you clean up a conn, if it is last apply
974      *       logic as though it is cleanupAllConnections
975      *
976      * @param cause for the clean up.
977      */
978
979     @Override
980     protected void onCleanUpAllConnections(String cause) {
981         cleanUpAllConnections(true, cause);
982     }
983
984     protected void cleanUpConnection(boolean tearDown, ApnContext apnContext) {
985
986         if (apnContext == null) {
987             if (DBG) log("cleanUpConnection: apn context is null");
988             return;
989         }
990
991         DcAsyncChannel dcac = apnContext.getDcAc();
992         if (DBG) {
993             log("cleanUpConnection: E tearDown=" + tearDown + " reason=" + apnContext.getReason() +
994                     " apnContext=" + apnContext);
995         }
996         if (tearDown) {
997             if (apnContext.isDisconnected()) {
998                 // The request is tearDown and but ApnContext is not connected.
999                 // If apnContext is not enabled anymore, break the linkage to the DCAC/DC.
1000                 apnContext.setState(DctConstants.State.IDLE);
1001                 if (!apnContext.isReady()) {
1002                     if (dcac != null) {
1003                         if (DBG) {
1004                             log("cleanUpConnection: teardown, disconnected, !ready apnContext="
1005                                     + apnContext);
1006                         }
1007                         dcac.tearDown(apnContext, "", null);
1008                     }
1009                     apnContext.setDataConnectionAc(null);
1010                 }
1011             } else {
1012                 // Connection is still there. Try to clean up.
1013                 if (dcac != null) {
1014                     if (apnContext.getState() != DctConstants.State.DISCONNECTING) {
1015                         boolean disconnectAll = false;
1016                         if (PhoneConstants.APN_TYPE_DUN.equals(apnContext.getApnType())) {
1017                             // CAF_MSIM is this below condition required.
1018                             // if (PhoneConstants.APN_TYPE_DUN.equals(PhoneConstants.APN_TYPE_DEFAULT)) {
1019                             if (teardownForDun()) {
1020                                 if (DBG) {
1021                                     log("cleanUpConnection: disconnectAll DUN connection");
1022                                 }
1023                                 // we need to tear it down - we brought it up just for dun and
1024                                 // other people are camped on it and now dun is done.  We need
1025                                 // to stop using it and let the normal apn list get used to find
1026                                 // connections for the remaining desired connections
1027                                 disconnectAll = true;
1028                             }
1029                         }
1030                         if (DBG) {
1031                             log("cleanUpConnection: tearing down" + (disconnectAll ? " all" :"")
1032                                     + "apnContext=" + apnContext);
1033                         }
1034                         Message msg = obtainMessage(DctConstants.EVENT_DISCONNECT_DONE, apnContext);
1035                         if (disconnectAll) {
1036                             apnContext.getDcAc().tearDownAll(apnContext.getReason(), msg);
1037                         } else {
1038                             apnContext.getDcAc()
1039                                 .tearDown(apnContext, apnContext.getReason(), msg);
1040                         }
1041                         apnContext.setState(DctConstants.State.DISCONNECTING);
1042                         mDisconnectPendingCount++;
1043                     }
1044                 } else {
1045                     // apn is connected but no reference to dcac.
1046                     // Should not be happen, but reset the state in case.
1047                     apnContext.setState(DctConstants.State.IDLE);
1048                     mPhone.notifyDataConnection(apnContext.getReason(),
1049                                                 apnContext.getApnType());
1050                 }
1051             }
1052         } else {
1053             // force clean up the data connection.
1054             if (dcac != null) dcac.reqReset();
1055             apnContext.setState(DctConstants.State.IDLE);
1056             mPhone.notifyDataConnection(apnContext.getReason(), apnContext.getApnType());
1057             apnContext.setDataConnectionAc(null);
1058         }
1059
1060         // Make sure reconnection alarm is cleaned up if there is no ApnContext
1061         // associated to the connection.
1062         if (dcac != null) {
1063             cancelReconnectAlarm(apnContext);
1064         }
1065         if (DBG) {
1066             log("cleanUpConnection: X tearDown=" + tearDown + " reason=" + apnContext.getReason() +
1067                     " apnContext=" + apnContext + " dcac=" + apnContext.getDcAc());
1068         }
1069     }
1070
1071     /**
1072      * Determine if DUN connection is special and we need to teardown on start/stop
1073      */
1074     private boolean teardownForDun() {
1075         // CDMA always needs to do this the profile id is correct
1076         final int rilRat = mPhone.getServiceState().getRilDataRadioTechnology();
1077         if (ServiceState.isCdma(rilRat)) return true;
1078
1079         return (fetchDunApn() != null);
1080     }
1081
1082     /**
1083      * Cancels the alarm associated with apnContext.
1084      *
1085      * @param apnContext on which the alarm should be stopped.
1086      */
1087     private void cancelReconnectAlarm(ApnContext apnContext) {
1088         if (apnContext == null) return;
1089
1090         PendingIntent intent = apnContext.getReconnectIntent();
1091
1092         if (intent != null) {
1093                 AlarmManager am =
1094                     (AlarmManager) mPhone.getContext().getSystemService(Context.ALARM_SERVICE);
1095                 am.cancel(intent);
1096                 apnContext.setReconnectIntent(null);
1097         }
1098     }
1099
1100     /**
1101      * @param types comma delimited list of APN types
1102      * @return array of APN types
1103      */
1104     private String[] parseTypes(String types) {
1105         String[] result;
1106         // If unset, set to DEFAULT.
1107         if (types == null || types.equals("")) {
1108             result = new String[1];
1109             result[0] = PhoneConstants.APN_TYPE_ALL;
1110         } else {
1111             result = types.split(",");
1112         }
1113         return result;
1114     }
1115
1116     @Override
1117     protected boolean isPermanentFail(DcFailCause dcFailCause) {
1118         return (dcFailCause.isPermanentFail() &&
1119                 (mAttached.get() == false || dcFailCause != DcFailCause.SIGNAL_LOST));
1120     }
1121
1122     private ApnSetting makeApnSetting(Cursor cursor) {
1123         String[] types = parseTypes(
1124                 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.TYPE)));
1125         ApnSetting apn = new ApnSetting(
1126                 cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers._ID)),
1127                 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.NUMERIC)),
1128                 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.NAME)),
1129                 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.APN)),
1130                 NetworkUtils.trimV4AddrZeros(
1131                         cursor.getString(
1132                         cursor.getColumnIndexOrThrow(Telephony.Carriers.PROXY))),
1133                 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.PORT)),
1134                 NetworkUtils.trimV4AddrZeros(
1135                         cursor.getString(
1136                         cursor.getColumnIndexOrThrow(Telephony.Carriers.MMSC))),
1137                 NetworkUtils.trimV4AddrZeros(
1138                         cursor.getString(
1139                         cursor.getColumnIndexOrThrow(Telephony.Carriers.MMSPROXY))),
1140                 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.MMSPORT)),
1141                 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.USER)),
1142                 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.PASSWORD)),
1143                 cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers.AUTH_TYPE)),
1144                 types,
1145                 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.PROTOCOL)),
1146                 cursor.getString(cursor.getColumnIndexOrThrow(
1147                         Telephony.Carriers.ROAMING_PROTOCOL)),
1148                 cursor.getInt(cursor.getColumnIndexOrThrow(
1149                         Telephony.Carriers.CARRIER_ENABLED)) == 1,
1150                 cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers.BEARER)),
1151                 cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers.BEARER_BITMASK)),
1152                 cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers.PROFILE_ID)),
1153                 cursor.getInt(cursor.getColumnIndexOrThrow(
1154                         Telephony.Carriers.MODEM_COGNITIVE)) == 1,
1155                 cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers.MAX_CONNS)),
1156                 cursor.getInt(cursor.getColumnIndexOrThrow(
1157                         Telephony.Carriers.WAIT_TIME)),
1158                 cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers.MAX_CONNS_TIME)),
1159                 cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers.MTU)),
1160                 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.MVNO_TYPE)),
1161                 cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.MVNO_MATCH_DATA)));
1162         return apn;
1163     }
1164
1165     private ArrayList<ApnSetting> createApnList(Cursor cursor) {
1166         ArrayList<ApnSetting> mnoApns = new ArrayList<ApnSetting>();
1167         ArrayList<ApnSetting> mvnoApns = new ArrayList<ApnSetting>();
1168         IccRecords r = mIccRecords.get();
1169
1170         if (cursor.moveToFirst()) {
1171             do {
1172                 ApnSetting apn = makeApnSetting(cursor);
1173                 if (apn == null) {
1174                     continue;
1175                 }
1176
1177                 if (apn.hasMvnoParams()) {
1178                     if (r != null && ApnSetting.mvnoMatches(r, apn.mvnoType, apn.mvnoMatchData)) {
1179                         mvnoApns.add(apn);
1180                     }
1181                 } else {
1182                     mnoApns.add(apn);
1183                 }
1184             } while (cursor.moveToNext());
1185         }
1186
1187         ArrayList<ApnSetting> result = mvnoApns.isEmpty() ? mnoApns : mvnoApns;
1188         if (DBG) log("createApnList: X result=" + result);
1189         return result;
1190     }
1191
1192     private boolean dataConnectionNotInUse(DcAsyncChannel dcac) {
1193         if (DBG) log("dataConnectionNotInUse: check if dcac is inuse dcac=" + dcac);
1194         for (ApnContext apnContext : mApnContexts.values()) {
1195             if (apnContext.getDcAc() == dcac) {
1196                 if (DBG) log("dataConnectionNotInUse: in use by apnContext=" + apnContext);
1197                 return false;
1198             }
1199         }
1200         // TODO: Fix retry handling so free DataConnections have empty apnlists.
1201         // Probably move retry handling into DataConnections and reduce complexity
1202         // of DCT.
1203         if (DBG) log("dataConnectionNotInUse: tearDownAll");
1204         dcac.tearDownAll("No connection", null);
1205         if (DBG) log("dataConnectionNotInUse: not in use return true");
1206         return true;
1207     }
1208
1209     private DcAsyncChannel findFreeDataConnection() {
1210         for (DcAsyncChannel dcac : mDataConnectionAcHashMap.values()) {
1211             if (dcac.isInactiveSync() && dataConnectionNotInUse(dcac)) {
1212                 if (DBG) {
1213                     log("findFreeDataConnection: found free DataConnection=" +
1214                         " dcac=" + dcac);
1215                 }
1216                 return dcac;
1217             }
1218         }
1219         log("findFreeDataConnection: NO free DataConnection");
1220         return null;
1221     }
1222
1223     private boolean setupData(ApnContext apnContext, int radioTech) {
1224         if (DBG) log("setupData: apnContext=" + apnContext);
1225         ApnSetting apnSetting;
1226         DcAsyncChannel dcac = null;
1227
1228         apnSetting = apnContext.getNextWaitingApn();
1229         if (apnSetting == null) {
1230             if (DBG) log("setupData: return for no apn found!");
1231             return false;
1232         }
1233
1234         int profileId = apnSetting.profileId;
1235         if (profileId == 0) {
1236             profileId = getApnProfileID(apnContext.getApnType());
1237         }
1238
1239         // On CDMA, if we're explicitly asking for DUN, we need have
1240         // a dun-profiled connection so we can't share an existing one
1241         // On GSM/LTE we can share existing apn connections provided they support
1242         // this type.
1243         if (apnContext.getApnType() != PhoneConstants.APN_TYPE_DUN ||
1244                 teardownForDun() == false) {
1245             dcac = checkForCompatibleConnectedApnContext(apnContext);
1246             if (dcac != null) {
1247                 // Get the dcacApnSetting for the connection we want to share.
1248                 ApnSetting dcacApnSetting = dcac.getApnSettingSync();
1249                 if (dcacApnSetting != null) {
1250                     // Setting is good, so use it.
1251                     apnSetting = dcacApnSetting;
1252                 }
1253             }
1254         }
1255         if (dcac == null) {
1256             if (isOnlySingleDcAllowed(radioTech)) {
1257                 if (isHigherPriorityApnContextActive(apnContext)) {
1258                     if (DBG) {
1259                         log("setupData: Higher priority ApnContext active.  Ignoring call");
1260                     }
1261                     return false;
1262                 }
1263
1264                 // Only lower priority calls left.  Disconnect them all in this single PDP case
1265                 // so that we can bring up the requested higher priority call (once we receive
1266                 // repsonse for deactivate request for the calls we are about to disconnect
1267                 if (cleanUpAllConnections(true, Phone.REASON_SINGLE_PDN_ARBITRATION)) {
1268                     // If any call actually requested to be disconnected, means we can't
1269                     // bring up this connection yet as we need to wait for those data calls
1270                     // to be disconnected.
1271                     if (DBG) log("setupData: Some calls are disconnecting first.  Wait and retry");
1272                     return false;
1273                 }
1274
1275                 // No other calls are active, so proceed
1276                 if (DBG) log("setupData: Single pdp. Continue setting up data call.");
1277             }
1278
1279             dcac = findFreeDataConnection();
1280
1281             if (dcac == null) {
1282                 dcac = createDataConnection();
1283             }
1284
1285             if (dcac == null) {
1286                 if (DBG) log("setupData: No free DataConnection and couldn't create one, WEIRD");
1287                 return false;
1288             }
1289         }
1290         if (DBG) log("setupData: dcac=" + dcac + " apnSetting=" + apnSetting);
1291
1292         apnContext.setDataConnectionAc(dcac);
1293         apnContext.setApnSetting(apnSetting);
1294         apnContext.setState(DctConstants.State.CONNECTING);
1295         mPhone.notifyDataConnection(apnContext.getReason(), apnContext.getApnType());
1296
1297         Message msg = obtainMessage();
1298         msg.what = DctConstants.EVENT_DATA_SETUP_COMPLETE;
1299         msg.obj = apnContext;
1300         dcac.bringUp(apnContext, getInitialMaxRetry(), profileId, radioTech, mAutoAttachOnCreation,
1301                 msg);
1302
1303         if (DBG) log("setupData: initing!");
1304         return true;
1305     }
1306
1307     /**
1308      * Handles changes to the APN database.
1309      */
1310     private void onApnChanged() {
1311         DctConstants.State overallState = getOverallState();
1312         boolean isDisconnected = (overallState == DctConstants.State.IDLE ||
1313                 overallState == DctConstants.State.FAILED);
1314
1315         if (mPhone instanceof GSMPhone) {
1316             // The "current" may no longer be valid.  MMS depends on this to send properly. TBD
1317             ((GSMPhone)mPhone).updateCurrentCarrierInProvider();
1318         }
1319
1320         // TODO: It'd be nice to only do this if the changed entrie(s)
1321         // match the current operator.
1322         if (DBG) log("onApnChanged: createAllApnList and cleanUpAllConnections");
1323         createAllApnList();
1324         setInitialAttachApn();
1325         cleanUpConnectionsOnUpdatedApns(!isDisconnected);
1326
1327         // FIXME: See bug 17426028 maybe no conditional is needed.
1328         if (mPhone.getSubId() == SubscriptionManager.getDefaultDataSubId()) {
1329             setupDataOnConnectableApns(Phone.REASON_APN_CHANGED);
1330         }
1331     }
1332
1333     /**
1334      * @param cid Connection id provided from RIL.
1335      * @return DataConnectionAc associated with specified cid.
1336      */
1337     private DcAsyncChannel findDataConnectionAcByCid(int cid) {
1338         for (DcAsyncChannel dcac : mDataConnectionAcHashMap.values()) {
1339             if (dcac.getCidSync() == cid) {
1340                 return dcac;
1341             }
1342         }
1343         return null;
1344     }
1345
1346     // TODO: For multiple Active APNs not exactly sure how to do this.
1347     @Override
1348     protected void gotoIdleAndNotifyDataConnection(String reason) {
1349         if (DBG) log("gotoIdleAndNotifyDataConnection: reason=" + reason);
1350         notifyDataConnection(reason);
1351         mActiveApn = null;
1352     }
1353
1354     /**
1355      * "Active" here means ApnContext isEnabled() and not in FAILED state
1356      * @param apnContext to compare with
1357      * @return true if higher priority active apn found
1358      */
1359     private boolean isHigherPriorityApnContextActive(ApnContext apnContext) {
1360         for (ApnContext otherContext : mPrioritySortedApnContexts) {
1361             if (apnContext.getApnType().equalsIgnoreCase(otherContext.getApnType())) return false;
1362             if (otherContext.isEnabled() && otherContext.getState() != DctConstants.State.FAILED) {
1363                 return true;
1364             }
1365         }
1366         return false;
1367     }
1368
1369     /**
1370      * Reports if we support multiple connections or not.
1371      * This is a combination of factors, based on carrier and RAT.
1372      * @param rilRadioTech the RIL Radio Tech currently in use
1373      * @return true if only single DataConnection is allowed
1374      */
1375     private boolean isOnlySingleDcAllowed(int rilRadioTech) {
1376         int[] singleDcRats = mPhone.getContext().getResources().getIntArray(
1377                 com.android.internal.R.array.config_onlySingleDcAllowed);
1378         boolean onlySingleDcAllowed = false;
1379         if (Build.IS_DEBUGGABLE &&
1380                 SystemProperties.getBoolean("persist.telephony.test.singleDc", false)) {
1381             onlySingleDcAllowed = true;
1382         }
1383         if (singleDcRats != null) {
1384             for (int i=0; i < singleDcRats.length && onlySingleDcAllowed == false; i++) {
1385                 if (rilRadioTech == singleDcRats[i]) onlySingleDcAllowed = true;
1386             }
1387         }
1388
1389         if (DBG) log("isOnlySingleDcAllowed(" + rilRadioTech + "): " + onlySingleDcAllowed);
1390         return onlySingleDcAllowed;
1391     }
1392
1393     @Override
1394     protected void restartRadio() {
1395         if (DBG) log("restartRadio: ************TURN OFF RADIO**************");
1396         cleanUpAllConnections(true, Phone.REASON_RADIO_TURNED_OFF);
1397         mPhone.getServiceStateTracker().powerOffRadioSafely(this);
1398         /* Note: no need to call setRadioPower(true).  Assuming the desired
1399          * radio power state is still ON (as tracked by ServiceStateTracker),
1400          * ServiceStateTracker will call setRadioPower when it receives the
1401          * RADIO_STATE_CHANGED notification for the power off.  And if the
1402          * desired power state has changed in the interim, we don't want to
1403          * override it with an unconditional power on.
1404          */
1405
1406         int reset = Integer.parseInt(SystemProperties.get("net.ppp.reset-by-timeout", "0"));
1407         SystemProperties.set("net.ppp.reset-by-timeout", String.valueOf(reset+1));
1408     }
1409
1410     /**
1411      * Return true if data connection need to be setup after disconnected due to
1412      * reason.
1413      *
1414      * @param reason the reason why data is disconnected
1415      * @return true if try setup data connection is need for this reason
1416      */
1417     private boolean retryAfterDisconnected(ApnContext apnContext) {
1418         boolean retry = true;
1419         String reason = apnContext.getReason();
1420
1421         if ( Phone.REASON_RADIO_TURNED_OFF.equals(reason) ||
1422                 (isOnlySingleDcAllowed(mPhone.getServiceState().getRilDataRadioTechnology())
1423                  && isHigherPriorityApnContextActive(apnContext))) {
1424             retry = false;
1425         }
1426         return retry;
1427     }
1428
1429     private void startAlarmForReconnect(int delay, ApnContext apnContext) {
1430         String apnType = apnContext.getApnType();
1431
1432         Intent intent = new Intent(INTENT_RECONNECT_ALARM + "." + apnType);
1433         intent.putExtra(INTENT_RECONNECT_ALARM_EXTRA_REASON, apnContext.getReason());
1434         intent.putExtra(INTENT_RECONNECT_ALARM_EXTRA_TYPE, apnType);
1435
1436         // Get current sub id.
1437         int subId = SubscriptionManager.getDefaultDataSubId();
1438         intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, subId);
1439
1440         if (DBG) {
1441             log("startAlarmForReconnect: delay=" + delay + " action=" + intent.getAction()
1442                     + " apn=" + apnContext);
1443         }
1444
1445         PendingIntent alarmIntent = PendingIntent.getBroadcast (mPhone.getContext(), 0,
1446                                         intent, PendingIntent.FLAG_UPDATE_CURRENT);
1447         apnContext.setReconnectIntent(alarmIntent);
1448         mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
1449                 SystemClock.elapsedRealtime() + delay, alarmIntent);
1450     }
1451
1452     private void startAlarmForRestartTrySetup(int delay, ApnContext apnContext) {
1453         String apnType = apnContext.getApnType();
1454         Intent intent = new Intent(INTENT_RESTART_TRYSETUP_ALARM + "." + apnType);
1455         intent.putExtra(INTENT_RESTART_TRYSETUP_ALARM_EXTRA_TYPE, apnType);
1456
1457         if (DBG) {
1458             log("startAlarmForRestartTrySetup: delay=" + delay + " action=" + intent.getAction()
1459                     + " apn=" + apnContext);
1460         }
1461         PendingIntent alarmIntent = PendingIntent.getBroadcast (mPhone.getContext(), 0,
1462                                         intent, PendingIntent.FLAG_UPDATE_CURRENT);
1463         apnContext.setReconnectIntent(alarmIntent);
1464         mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
1465                 SystemClock.elapsedRealtime() + delay, alarmIntent);
1466     }
1467
1468     private void notifyNoData(DcFailCause lastFailCauseCode,
1469                               ApnContext apnContext) {
1470         if (DBG) log( "notifyNoData: type=" + apnContext.getApnType());
1471         if (isPermanentFail(lastFailCauseCode)
1472             && (!apnContext.getApnType().equals(PhoneConstants.APN_TYPE_DEFAULT))) {
1473             mPhone.notifyDataConnectionFailed(apnContext.getReason(), apnContext.getApnType());
1474         }
1475     }
1476
1477     private void onRecordsLoaded() {
1478         if (DBG) log("onRecordsLoaded: createAllApnList");
1479         mAutoAttachOnCreationConfig = mPhone.getContext().getResources()
1480                 .getBoolean(com.android.internal.R.bool.config_auto_attach_data_on_creation);
1481
1482         createAllApnList();
1483         setInitialAttachApn();
1484         if (mPhone.mCi.getRadioState().isOn()) {
1485             if (DBG) log("onRecordsLoaded: notifying data availability");
1486             notifyOffApnsOfAvailability(Phone.REASON_SIM_LOADED);
1487         }
1488         setupDataOnConnectableApns(Phone.REASON_SIM_LOADED);
1489     }
1490
1491     private void onSimNotReady() {
1492         if (DBG) log("onSimNotReady");
1493
1494         cleanUpAllConnections(true, Phone.REASON_SIM_NOT_READY);
1495         mAllApnSettings = null;
1496         mAutoAttachOnCreationConfig = false;
1497     }
1498
1499     @Override
1500     protected void onSetDependencyMet(String apnType, boolean met) {
1501         // don't allow users to tweak hipri to work around default dependency not met
1502         if (PhoneConstants.APN_TYPE_HIPRI.equals(apnType)) return;
1503
1504         ApnContext apnContext = mApnContexts.get(apnType);
1505         if (apnContext == null) {
1506             loge("onSetDependencyMet: ApnContext not found in onSetDependencyMet(" +
1507                     apnType + ", " + met + ")");
1508             return;
1509         }
1510         applyNewState(apnContext, apnContext.isEnabled(), met);
1511         if (PhoneConstants.APN_TYPE_DEFAULT.equals(apnType)) {
1512             // tie actions on default to similar actions on HIPRI regarding dependencyMet
1513             apnContext = mApnContexts.get(PhoneConstants.APN_TYPE_HIPRI);
1514             if (apnContext != null) applyNewState(apnContext, apnContext.isEnabled(), met);
1515         }
1516     }
1517
1518     private void applyNewState(ApnContext apnContext, boolean enabled, boolean met) {
1519         boolean cleanup = false;
1520         boolean trySetup = false;
1521         if (DBG) {
1522             log("applyNewState(" + apnContext.getApnType() + ", " + enabled +
1523                     "(" + apnContext.isEnabled() + "), " + met + "(" +
1524                     apnContext.getDependencyMet() +"))");
1525         }
1526         if (apnContext.isReady()) {
1527             cleanup = true;
1528             if (enabled && met) {
1529                 DctConstants.State state = apnContext.getState();
1530                 switch(state) {
1531                     case CONNECTING:
1532                     case SCANNING:
1533                     case CONNECTED:
1534                     case DISCONNECTING:
1535                         // We're "READY" and active so just return
1536                         if (DBG) log("applyNewState: 'ready' so return");
1537                         return;
1538                     case IDLE:
1539                         // fall through: this is unexpected but if it happens cleanup and try setup
1540                     case FAILED:
1541                     case RETRYING: {
1542                         // We're "READY" but not active so disconnect (cleanup = true) and
1543                         // connect (trySetup = true) to be sure we retry the connection.
1544                         trySetup = true;
1545                         apnContext.setReason(Phone.REASON_DATA_ENABLED);
1546                         break;
1547                     }
1548                 }
1549             } else if (met) {
1550                 apnContext.setReason(Phone.REASON_DATA_DISABLED);
1551                 // If ConnectivityService has disabled this network, stop trying to bring
1552                 // it up, but do not tear it down - ConnectivityService will do that
1553                 // directly by talking with the DataConnection.
1554                 //
1555                 // This doesn't apply to DUN, however.  Those connections have special
1556                 // requirements from carriers and we need stop using them when the dun
1557                 // request goes away.  This applies to both CDMA and GSM because they both
1558                 // can declare the DUN APN sharable by default traffic, thus still satisfying
1559                 // those requests and not torn down organically.
1560                 if (apnContext.getApnType() == PhoneConstants.APN_TYPE_DUN && teardownForDun()) {
1561                     cleanup = true;
1562                 } else {
1563                     cleanup = false;
1564                 }
1565             } else {
1566                 apnContext.setReason(Phone.REASON_DATA_DEPENDENCY_UNMET);
1567             }
1568         } else {
1569             if (enabled && met) {
1570                 if (apnContext.isEnabled()) {
1571                     apnContext.setReason(Phone.REASON_DATA_DEPENDENCY_MET);
1572                 } else {
1573                     apnContext.setReason(Phone.REASON_DATA_ENABLED);
1574                 }
1575                 if (apnContext.getState() == DctConstants.State.FAILED) {
1576                     apnContext.setState(DctConstants.State.IDLE);
1577                 }
1578                 trySetup = true;
1579             }
1580         }
1581         apnContext.setEnabled(enabled);
1582         apnContext.setDependencyMet(met);
1583         if (cleanup) cleanUpConnection(true, apnContext);
1584         if (trySetup) trySetupData(apnContext);
1585     }
1586
1587     private DcAsyncChannel checkForCompatibleConnectedApnContext(ApnContext apnContext) {
1588         String apnType = apnContext.getApnType();
1589         ApnSetting dunSetting = null;
1590
1591         if (PhoneConstants.APN_TYPE_DUN.equals(apnType)) {
1592             dunSetting = fetchDunApn();
1593         }
1594         if (DBG) {
1595             log("checkForCompatibleConnectedApnContext: apnContext=" + apnContext );
1596         }
1597
1598         DcAsyncChannel potentialDcac = null;
1599         ApnContext potentialApnCtx = null;
1600         for (ApnContext curApnCtx : mApnContexts.values()) {
1601             DcAsyncChannel curDcac = curApnCtx.getDcAc();
1602             if (curDcac != null) {
1603                 ApnSetting apnSetting = curApnCtx.getApnSetting();
1604                 log("apnSetting: " + apnSetting);
1605                 if (dunSetting != null) {
1606                     if (dunSetting.equals(apnSetting)) {
1607                         switch (curApnCtx.getState()) {
1608                             case CONNECTED:
1609                                 if (DBG) {
1610                                     log("checkForCompatibleConnectedApnContext:"
1611                                             + " found dun conn=" + curDcac
1612                                             + " curApnCtx=" + curApnCtx);
1613                                 }
1614                                 return curDcac;
1615                             case RETRYING:
1616                             case CONNECTING:
1617                                 potentialDcac = curDcac;
1618                                 potentialApnCtx = curApnCtx;
1619                             default:
1620                                 // Not connected, potential unchanged
1621                                 break;
1622                         }
1623                     }
1624                 } else if (apnSetting != null && apnSetting.canHandleType(apnType)) {
1625                     switch (curApnCtx.getState()) {
1626                         case CONNECTED:
1627                             if (DBG) {
1628                                 log("checkForCompatibleConnectedApnContext:"
1629                                         + " found canHandle conn=" + curDcac
1630                                         + " curApnCtx=" + curApnCtx);
1631                             }
1632                             return curDcac;
1633                         case RETRYING:
1634                         case CONNECTING:
1635                             potentialDcac = curDcac;
1636                             potentialApnCtx = curApnCtx;
1637                         default:
1638                             // Not connected, potential unchanged
1639                             break;
1640                     }
1641                 }
1642             } else {
1643                 if (VDBG) {
1644                     log("checkForCompatibleConnectedApnContext: not conn curApnCtx=" + curApnCtx);
1645                 }
1646             }
1647         }
1648         if (potentialDcac != null) {
1649             if (DBG) {
1650                 log("checkForCompatibleConnectedApnContext: found potential conn=" + potentialDcac
1651                         + " curApnCtx=" + potentialApnCtx);
1652             }
1653             return potentialDcac;
1654         }
1655
1656         if (DBG) log("checkForCompatibleConnectedApnContext: NO conn apnContext=" + apnContext);
1657         return null;
1658     }
1659
1660     @Override
1661     protected void onEnableApn(int apnId, int enabled) {
1662         ApnContext apnContext = mApnContexts.get(apnIdToType(apnId));
1663         if (apnContext == null) {
1664             loge("onEnableApn(" + apnId + ", " + enabled + "): NO ApnContext");
1665             return;
1666         }
1667         // TODO change our retry manager to use the appropriate numbers for the new APN
1668         if (DBG) log("onEnableApn: apnContext=" + apnContext + " call applyNewState");
1669         applyNewState(apnContext, enabled == DctConstants.ENABLED, apnContext.getDependencyMet());
1670     }
1671
1672     @Override
1673     // TODO: We shouldnt need this.
1674     protected boolean onTrySetupData(String reason) {
1675         if (DBG) log("onTrySetupData: reason=" + reason);
1676         setupDataOnConnectableApns(reason);
1677         return true;
1678     }
1679
1680     protected boolean onTrySetupData(ApnContext apnContext) {
1681         if (DBG) log("onTrySetupData: apnContext=" + apnContext);
1682         return trySetupData(apnContext);
1683     }
1684
1685     @Override
1686     protected void onRoamingOff() {
1687         if (DBG) log("onRoamingOff");
1688
1689         if (!mUserDataEnabled) return;
1690
1691         if (getDataOnRoamingEnabled() == false) {
1692             notifyOffApnsOfAvailability(Phone.REASON_ROAMING_OFF);
1693             setupDataOnConnectableApns(Phone.REASON_ROAMING_OFF);
1694         } else {
1695             notifyDataConnection(Phone.REASON_ROAMING_OFF);
1696         }
1697     }
1698
1699     @Override
1700     protected void onRoamingOn() {
1701         if (DBG) log("onRoamingOn");
1702
1703         if (!mUserDataEnabled) return;
1704
1705         if (getDataOnRoamingEnabled()) {
1706             if (DBG) log("onRoamingOn: setup data on roaming");
1707             setupDataOnConnectableApns(Phone.REASON_ROAMING_ON);
1708             notifyDataConnection(Phone.REASON_ROAMING_ON);
1709         } else {
1710             if (DBG) log("onRoamingOn: Tear down data connection on roaming.");
1711             cleanUpAllConnections(true, Phone.REASON_ROAMING_ON);
1712             notifyOffApnsOfAvailability(Phone.REASON_ROAMING_ON);
1713         }
1714     }
1715
1716     @Override
1717     protected void onRadioAvailable() {
1718         if (DBG) log("onRadioAvailable");
1719         if (mPhone.getSimulatedRadioControl() != null) {
1720             // Assume data is connected on the simulator
1721             // FIXME  this can be improved
1722             // setState(DctConstants.State.CONNECTED);
1723             notifyDataConnection(null);
1724
1725             log("onRadioAvailable: We're on the simulator; assuming data is connected");
1726         }
1727
1728         IccRecords r = mIccRecords.get();
1729         if (r != null && r.getRecordsLoaded()) {
1730             notifyOffApnsOfAvailability(null);
1731         }
1732
1733         if (getOverallState() != DctConstants.State.IDLE) {
1734             cleanUpConnection(true, null);
1735         }
1736     }
1737
1738     @Override
1739     protected void onRadioOffOrNotAvailable() {
1740         // Make sure our reconnect delay starts at the initial value
1741         // next time the radio comes on
1742
1743         mReregisterOnReconnectFailure = false;
1744
1745         if (mPhone.getSimulatedRadioControl() != null) {
1746             // Assume data is connected on the simulator
1747             // FIXME  this can be improved
1748             log("We're on the simulator; assuming radio off is meaningless");
1749         } else {
1750             if (DBG) log("onRadioOffOrNotAvailable: is off and clean up all connections");
1751             cleanUpAllConnections(false, Phone.REASON_RADIO_TURNED_OFF);
1752         }
1753         notifyOffApnsOfAvailability(null);
1754     }
1755
1756     @Override
1757     protected void completeConnection(ApnContext apnContext) {
1758         boolean isProvApn = apnContext.isProvisioningApn();
1759
1760         if (DBG) log("completeConnection: successful, notify the world apnContext=" + apnContext);
1761
1762         if (mIsProvisioning && !TextUtils.isEmpty(mProvisioningUrl)) {
1763             if (DBG) {
1764                 log("completeConnection: MOBILE_PROVISIONING_ACTION url="
1765                         + mProvisioningUrl);
1766             }
1767             Intent newIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN,
1768                     Intent.CATEGORY_APP_BROWSER);
1769             newIntent.setData(Uri.parse(mProvisioningUrl));
1770             newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
1771                     Intent.FLAG_ACTIVITY_NEW_TASK);
1772             try {
1773                 mPhone.getContext().startActivity(newIntent);
1774             } catch (ActivityNotFoundException e) {
1775                 loge("completeConnection: startActivityAsUser failed" + e);
1776             }
1777         }
1778         mIsProvisioning = false;
1779         mProvisioningUrl = null;
1780         if (mProvisioningSpinner != null) {
1781             sendMessage(obtainMessage(DctConstants.CMD_CLEAR_PROVISIONING_SPINNER,
1782                     mProvisioningSpinner));
1783         }
1784
1785         mPhone.notifyDataConnection(apnContext.getReason(), apnContext.getApnType());
1786         startNetStatPoll();
1787         startDataStallAlarm(DATA_STALL_NOT_SUSPECTED);
1788     }
1789
1790     /**
1791      * A SETUP (aka bringUp) has completed, possibly with an error. If
1792      * there is an error this method will call {@link #onDataSetupCompleteError}.
1793      */
1794     @Override
1795     protected void onDataSetupComplete(AsyncResult ar) {
1796
1797         DcFailCause cause = DcFailCause.UNKNOWN;
1798         boolean handleError = false;
1799         ApnContext apnContext = null;
1800
1801         if(ar.userObj instanceof ApnContext){
1802             apnContext = (ApnContext)ar.userObj;
1803         } else {
1804             throw new RuntimeException("onDataSetupComplete: No apnContext");
1805         }
1806
1807         if (ar.exception == null) {
1808             DcAsyncChannel dcac = apnContext.getDcAc();
1809
1810             if (RADIO_TESTS) {
1811                 // Note: To change radio.test.onDSC.null.dcac from command line you need to
1812                 // adb root and adb remount and from the command line you can only change the
1813                 // value to 1 once. To change it a second time you can reboot or execute
1814                 // adb shell stop and then adb shell start. The command line to set the value is:
1815                 // adb shell sqlite3 /data/data/com.android.providers.settings/databases/settings.db "insert into system (name,value) values ('radio.test.onDSC.null.dcac', '1');"
1816                 ContentResolver cr = mPhone.getContext().getContentResolver();
1817                 String radioTestProperty = "radio.test.onDSC.null.dcac";
1818                 if (Settings.System.getInt(cr, radioTestProperty, 0) == 1) {
1819                     log("onDataSetupComplete: " + radioTestProperty +
1820                             " is true, set dcac to null and reset property to false");
1821                     dcac = null;
1822                     Settings.System.putInt(cr, radioTestProperty, 0);
1823                     log("onDataSetupComplete: " + radioTestProperty + "=" +
1824                             Settings.System.getInt(mPhone.getContext().getContentResolver(),
1825                                     radioTestProperty, -1));
1826                 }
1827             }
1828             if (dcac == null) {
1829                 log("onDataSetupComplete: no connection to DC, handle as error");
1830                 cause = DcFailCause.CONNECTION_TO_DATACONNECTIONAC_BROKEN;
1831                 handleError = true;
1832             } else {
1833                 ApnSetting apn = apnContext.getApnSetting();
1834                 if (DBG) {
1835                     log("onDataSetupComplete: success apn=" + (apn == null ? "unknown" : apn.apn));
1836                 }
1837                 if (apn != null && apn.proxy != null && apn.proxy.length() != 0) {
1838                     try {
1839                         String port = apn.port;
1840                         if (TextUtils.isEmpty(port)) port = "8080";
1841                         ProxyInfo proxy = new ProxyInfo(apn.proxy,
1842                                 Integer.parseInt(port), null);
1843                         dcac.setLinkPropertiesHttpProxySync(proxy);
1844                     } catch (NumberFormatException e) {
1845                         loge("onDataSetupComplete: NumberFormatException making ProxyProperties (" +
1846                                 apn.port + "): " + e);
1847                     }
1848                 }
1849
1850                 // everything is setup
1851                 if(TextUtils.equals(apnContext.getApnType(),PhoneConstants.APN_TYPE_DEFAULT)) {
1852                     SystemProperties.set(PUPPET_MASTER_RADIO_STRESS_TEST, "true");
1853                     if (mCanSetPreferApn && mPreferredApn == null) {
1854                         if (DBG) log("onDataSetupComplete: PREFERED APN is null");
1855                         mPreferredApn = apn;
1856                         if (mPreferredApn != null) {
1857                             setPreferredApn(mPreferredApn.id);
1858                         }
1859                     }
1860                 } else {
1861                     SystemProperties.set(PUPPET_MASTER_RADIO_STRESS_TEST, "false");
1862                 }
1863
1864                 // A connection is setup
1865                 apnContext.setState(DctConstants.State.CONNECTED);
1866                 boolean isProvApn = apnContext.isProvisioningApn();
1867                 final ConnectivityManager cm = ConnectivityManager.from(mPhone.getContext());
1868                 if (mProvisionBroadcastReceiver != null) {
1869                     mPhone.getContext().unregisterReceiver(mProvisionBroadcastReceiver);
1870                     mProvisionBroadcastReceiver = null;
1871                 }
1872                 if ((!isProvApn) || mIsProvisioning) {
1873                     // Hide any provisioning notification.
1874                     cm.setProvisioningNotificationVisible(false, ConnectivityManager.TYPE_MOBILE,
1875                             mProvisionActionName);
1876                     // Complete the connection normally notifying the world we're connected.
1877                     // We do this if this isn't a special provisioning apn or if we've been
1878                     // told its time to provision.
1879                     completeConnection(apnContext);
1880                 } else {
1881                     // This is a provisioning APN that we're reporting as connected. Later
1882                     // when the user desires to upgrade this to a "default" connection,
1883                     // mIsProvisioning == true, we'll go through the code path above.
1884                     // mIsProvisioning becomes true when CMD_ENABLE_MOBILE_PROVISIONING
1885                     // is sent to the DCT.
1886                     if (DBG) {
1887                         log("onDataSetupComplete: successful, BUT send connected to prov apn as"
1888                                 + " mIsProvisioning:" + mIsProvisioning + " == false"
1889                                 + " && (isProvisioningApn:" + isProvApn + " == true");
1890                     }
1891
1892                     // While radio is up, grab provisioning URL.  The URL contains ICCID which
1893                     // disappears when radio is off.
1894                     mProvisionBroadcastReceiver = new ProvisionNotificationBroadcastReceiver(
1895                             cm.getMobileProvisioningUrl(),
1896                             TelephonyManager.getDefault().getNetworkOperatorName());
1897                     mPhone.getContext().registerReceiver(mProvisionBroadcastReceiver,
1898                             new IntentFilter(mProvisionActionName));
1899                     // Put up user notification that sign-in is required.
1900                     cm.setProvisioningNotificationVisible(true, ConnectivityManager.TYPE_MOBILE,
1901                             mProvisionActionName);
1902                     // Turn off radio to save battery and avoid wasting carrier resources.
1903                     // The network isn't usable and network validation will just fail anyhow.
1904                     setRadio(false);
1905
1906                     Intent intent = new Intent(
1907                             TelephonyIntents.ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN);
1908                     intent.putExtra(PhoneConstants.DATA_APN_KEY, apnContext.getApnSetting().apn);
1909                     intent.putExtra(PhoneConstants.DATA_APN_TYPE_KEY, apnContext.getApnType());
1910
1911                     String apnType = apnContext.getApnType();
1912                     LinkProperties linkProperties = getLinkProperties(apnType);
1913                     if (linkProperties != null) {
1914                         intent.putExtra(PhoneConstants.DATA_LINK_PROPERTIES_KEY, linkProperties);
1915                         String iface = linkProperties.getInterfaceName();
1916                         if (iface != null) {
1917                             intent.putExtra(PhoneConstants.DATA_IFACE_NAME_KEY, iface);
1918                         }
1919                     }
1920                     NetworkCapabilities networkCapabilities = getNetworkCapabilities(apnType);
1921                     if (networkCapabilities != null) {
1922                         intent.putExtra(PhoneConstants.DATA_NETWORK_CAPABILITIES_KEY,
1923                                 networkCapabilities);
1924                     }
1925
1926                     mPhone.getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1927                 }
1928                 if (DBG) {
1929                     log("onDataSetupComplete: SETUP complete type=" + apnContext.getApnType()
1930                         + ", reason:" + apnContext.getReason());
1931                 }
1932             }
1933         } else {
1934             cause = (DcFailCause) (ar.result);
1935             if (DBG) {
1936                 ApnSetting apn = apnContext.getApnSetting();
1937                 log(String.format("onDataSetupComplete: error apn=%s cause=%s",
1938                         (apn == null ? "unknown" : apn.apn), cause));
1939             }
1940             if (cause.isEventLoggable()) {
1941                 // Log this failure to the Event Logs.
1942                 int cid = getCellLocationId();
1943                 EventLog.writeEvent(EventLogTags.PDP_SETUP_FAIL,
1944                         cause.ordinal(), cid, TelephonyManager.getDefault().getNetworkType());
1945             }
1946             ApnSetting apn = apnContext.getApnSetting();
1947             mPhone.notifyPreciseDataConnectionFailed(apnContext.getReason(),
1948                     apnContext.getApnType(), apn != null ? apn.apn : "unknown", cause.toString());
1949
1950             // Count permanent failures and remove the APN we just tried
1951             if (isPermanentFail(cause)) apnContext.decWaitingApnsPermFailCount();
1952
1953             apnContext.removeWaitingApn(apnContext.getApnSetting());
1954             if (DBG) {
1955                 log(String.format("onDataSetupComplete: WaitingApns.size=%d" +
1956                         " WaitingApnsPermFailureCountDown=%d",
1957                         apnContext.getWaitingApns().size(),
1958                         apnContext.getWaitingApnsPermFailCount()));
1959             }
1960             handleError = true;
1961         }
1962
1963         if (handleError) {
1964             onDataSetupCompleteError(ar);
1965         }
1966
1967         /* If flag is set to false after SETUP_DATA_CALL is invoked, we need
1968          * to clean data connections.
1969          */
1970         if (!mInternalDataEnabled) {
1971             cleanUpAllConnections(null);
1972         }
1973
1974     }
1975
1976     /**
1977      * @return number of milli-seconds to delay between trying apns'
1978      */
1979     private int getApnDelay() {
1980         if (mFailFast) {
1981             return SystemProperties.getInt("persist.radio.apn_ff_delay",
1982                     APN_FAIL_FAST_DELAY_DEFAULT_MILLIS);
1983         } else {
1984             return SystemProperties.getInt("persist.radio.apn_delay", APN_DELAY_DEFAULT_MILLIS);
1985         }
1986     }
1987
1988     /**
1989      * Error has occurred during the SETUP {aka bringUP} request and the DCT
1990      * should either try the next waiting APN or start over from the
1991      * beginning if the list is empty. Between each SETUP request there will
1992      * be a delay defined by {@link #getApnDelay()}.
1993      */
1994     @Override
1995     protected void onDataSetupCompleteError(AsyncResult ar) {
1996         String reason = "";
1997         ApnContext apnContext = null;
1998
1999         if(ar.userObj instanceof ApnContext){
2000             apnContext = (ApnContext)ar.userObj;
2001         } else {
2002             throw new RuntimeException("onDataSetupCompleteError: No apnContext");
2003         }
2004
2005         // See if there are more APN's to try
2006         if (apnContext.getWaitingApns().isEmpty()) {
2007             apnContext.setState(DctConstants.State.FAILED);
2008             mPhone.notifyDataConnection(Phone.REASON_APN_FAILED, apnContext.getApnType());
2009
2010             apnContext.setDataConnectionAc(null);
2011
2012             if (apnContext.getWaitingApnsPermFailCount() == 0) {
2013                 if (DBG) {
2014                     log("onDataSetupCompleteError: All APN's had permanent failures, stop retrying");
2015                 }
2016             } else {
2017                 int delay = getApnDelay();
2018                 if (DBG) {
2019                     log("onDataSetupCompleteError: Not all APN's had permanent failures delay="
2020                             + delay);
2021                 }
2022                 startAlarmForRestartTrySetup(delay, apnContext);
2023             }
2024         } else {
2025             if (DBG) log("onDataSetupCompleteError: Try next APN");
2026             apnContext.setState(DctConstants.State.SCANNING);
2027             // Wait a bit before trying the next APN, so that
2028             // we're not tying up the RIL command channel
2029             startAlarmForReconnect(getApnDelay(), apnContext);
2030         }
2031     }
2032
2033     /**
2034      * Called when EVENT_DISCONNECT_DONE is received.
2035      */
2036     @Override
2037     protected void onDisconnectDone(int connId, AsyncResult ar) {
2038         ApnContext apnContext = null;
2039
2040         if (ar.userObj instanceof ApnContext) {
2041             apnContext = (ApnContext) ar.userObj;
2042         } else {
2043             loge("onDisconnectDone: Invalid ar in onDisconnectDone, ignore");
2044             return;
2045         }
2046
2047         if(DBG) log("onDisconnectDone: EVENT_DISCONNECT_DONE apnContext=" + apnContext);
2048         apnContext.setState(DctConstants.State.IDLE);
2049
2050         mPhone.notifyDataConnection(apnContext.getReason(), apnContext.getApnType());
2051
2052         // if all data connection are gone, check whether Airplane mode request was
2053         // pending.
2054         if (isDisconnected()) {
2055             if (mPhone.getServiceStateTracker().processPendingRadioPowerOffAfterDataOff()) {
2056                 if(DBG) log("onDisconnectDone: radio will be turned off, no retries");
2057                 // Radio will be turned off. No need to retry data setup
2058                 apnContext.setApnSetting(null);
2059                 apnContext.setDataConnectionAc(null);
2060
2061                 // Need to notify disconnect as well, in the case of switching Airplane mode.
2062                 // Otherwise, it would cause 30s delayed to turn on Airplane mode.
2063                 if (mDisconnectPendingCount > 0)
2064                     mDisconnectPendingCount--;
2065
2066                 if (mDisconnectPendingCount == 0) {
2067                     notifyDataDisconnectComplete();
2068                     notifyAllDataDisconnected();
2069                 }
2070                 return;
2071             }
2072         }
2073
2074         // If APN is still enabled, try to bring it back up automatically
2075         if (mAttached.get() && apnContext.isReady() && retryAfterDisconnected(apnContext)) {
2076             SystemProperties.set(PUPPET_MASTER_RADIO_STRESS_TEST, "false");
2077             // Wait a bit before trying the next APN, so that
2078             // we're not tying up the RIL command channel.
2079             // This also helps in any external dependency to turn off the context.
2080             if(DBG) log("onDisconnectDone: attached, ready and retry after disconnect");
2081             startAlarmForReconnect(getApnDelay(), apnContext);
2082         } else {
2083             boolean restartRadioAfterProvisioning = mPhone.getContext().getResources().getBoolean(
2084                     com.android.internal.R.bool.config_restartRadioAfterProvisioning);
2085
2086             if (apnContext.isProvisioningApn() && restartRadioAfterProvisioning) {
2087                 log("onDisconnectDone: restartRadio after provisioning");
2088                 restartRadio();
2089             }
2090             apnContext.setApnSetting(null);
2091             apnContext.setDataConnectionAc(null);
2092             if (isOnlySingleDcAllowed(mPhone.getServiceState().getRilDataRadioTechnology())) {
2093                 if(DBG) log("onDisconnectDone: isOnlySigneDcAllowed true so setup single apn");
2094                 setupDataOnConnectableApns(Phone.REASON_SINGLE_PDN_ARBITRATION);
2095             } else {
2096                 if(DBG) log("onDisconnectDone: not retrying");
2097             }
2098         }
2099
2100         if (mDisconnectPendingCount > 0)
2101             mDisconnectPendingCount--;
2102
2103         if (mDisconnectPendingCount == 0) {
2104             apnContext.setConcurrentVoiceAndDataAllowed(
2105                     mPhone.getServiceStateTracker().isConcurrentVoiceAndDataAllowed());
2106             notifyDataDisconnectComplete();
2107             notifyAllDataDisconnected();
2108         }
2109
2110     }
2111
2112     /**
2113      * Called when EVENT_DISCONNECT_DC_RETRYING is received.
2114      */
2115     @Override
2116     protected void onDisconnectDcRetrying(int connId, AsyncResult ar) {
2117         // We could just do this in DC!!!
2118         ApnContext apnContext = null;
2119
2120         if (ar.userObj instanceof ApnContext) {
2121             apnContext = (ApnContext) ar.userObj;
2122         } else {
2123             loge("onDisconnectDcRetrying: Invalid ar in onDisconnectDone, ignore");
2124             return;
2125         }
2126
2127         apnContext.setState(DctConstants.State.RETRYING);
2128         if(DBG) log("onDisconnectDcRetrying: apnContext=" + apnContext);
2129
2130         mPhone.notifyDataConnection(apnContext.getReason(), apnContext.getApnType());
2131     }
2132
2133
2134     @Override
2135     protected void onVoiceCallStarted() {
2136         if (DBG) log("onVoiceCallStarted");
2137         mInVoiceCall = true;
2138         if (isConnected() && ! mPhone.getServiceStateTracker().isConcurrentVoiceAndDataAllowed()) {
2139             if (DBG) log("onVoiceCallStarted stop polling");
2140             stopNetStatPoll();
2141             stopDataStallAlarm();
2142             notifyDataConnection(Phone.REASON_VOICE_CALL_STARTED);
2143         }
2144     }
2145
2146     @Override
2147     protected void onVoiceCallEnded() {
2148         if (DBG) log("onVoiceCallEnded");
2149         mInVoiceCall = false;
2150         if (isConnected()) {
2151             if (!mPhone.getServiceStateTracker().isConcurrentVoiceAndDataAllowed()) {
2152                 startNetStatPoll();
2153                 startDataStallAlarm(DATA_STALL_NOT_SUSPECTED);
2154                 notifyDataConnection(Phone.REASON_VOICE_CALL_ENDED);
2155             } else {
2156                 // clean slate after call end.
2157                 resetPollStats();
2158             }
2159         }
2160         // reset reconnect timer
2161         setupDataOnConnectableApns(Phone.REASON_VOICE_CALL_ENDED);
2162     }
2163
2164     @Override
2165     protected void onCleanUpConnection(boolean tearDown, int apnId, String reason) {
2166         if (DBG) log("onCleanUpConnection");
2167         ApnContext apnContext = mApnContexts.get(apnIdToType(apnId));
2168         if (apnContext != null) {
2169             apnContext.setReason(reason);
2170             cleanUpConnection(tearDown, apnContext);
2171         }
2172     }
2173
2174     @Override
2175     protected boolean isConnected() {
2176         for (ApnContext apnContext : mApnContexts.values()) {
2177             if (apnContext.getState() == DctConstants.State.CONNECTED) {
2178                 // At least one context is connected, return true
2179                 return true;
2180             }
2181         }
2182         // There are not any contexts connected, return false
2183         return false;
2184     }
2185
2186     @Override
2187     public boolean isDisconnected() {
2188         for (ApnContext apnContext : mApnContexts.values()) {
2189             if (!apnContext.isDisconnected()) {
2190                 // At least one context was not disconnected return false
2191                 return false;
2192             }
2193         }
2194         // All contexts were disconnected so return true
2195         return true;
2196     }
2197
2198     @Override
2199     protected void notifyDataConnection(String reason) {
2200         if (DBG) log("notifyDataConnection: reason=" + reason);
2201         for (ApnContext apnContext : mApnContexts.values()) {
2202             if (mAttached.get() && apnContext.isReady()) {
2203                 if (DBG) log("notifyDataConnection: type:" + apnContext.getApnType());
2204                 mPhone.notifyDataConnection(reason != null ? reason : apnContext.getReason(),
2205                         apnContext.getApnType());
2206             }
2207         }
2208         notifyOffApnsOfAvailability(reason);
2209     }
2210
2211     /**
2212      * Based on the sim operator numeric, create a list for all possible
2213      * Data Connections and setup the preferredApn.
2214      */
2215     private void createAllApnList() {
2216         mAllApnSettings = new ArrayList<ApnSetting>();
2217         IccRecords r = mIccRecords.get();
2218         String operator = (r != null) ? r.getOperatorNumeric() : "";
2219         if (operator != null) {
2220             String selection = "numeric = '" + operator + "'";
2221             // query only enabled apn.
2222             // carrier_enabled : 1 means enabled apn, 0 disabled apn.
2223             // selection += " and carrier_enabled = 1";
2224             if (DBG) log("createAllApnList: selection=" + selection);
2225
2226             Cursor cursor = mPhone.getContext().getContentResolver().query(
2227                     Telephony.Carriers.CONTENT_URI, null, selection, null, null);
2228
2229             if (cursor != null) {
2230                 if (cursor.getCount() > 0) {
2231                     mAllApnSettings = createApnList(cursor);
2232                 }
2233                 cursor.close();
2234             }
2235         }
2236
2237         addEmergencyApnSetting();
2238
2239         dedupeApnSettings();
2240
2241         if (mAllApnSettings.isEmpty()) {
2242             if (DBG) log("createAllApnList: No APN found for carrier: " + operator);
2243             mPreferredApn = null;
2244             // TODO: What is the right behavior?
2245             //notifyNoData(DataConnection.FailCause.MISSING_UNKNOWN_APN);
2246         } else {
2247             mPreferredApn = getPreferredApn();
2248             if (mPreferredApn != null && !mPreferredApn.numeric.equals(operator)) {
2249                 mPreferredApn = null;
2250                 setPreferredApn(-1);
2251             }
2252             if (DBG) log("createAllApnList: mPreferredApn=" + mPreferredApn);
2253         }
2254         if (DBG) log("createAllApnList: X mAllApnSettings=" + mAllApnSettings);
2255
2256         setDataProfilesAsNeeded();
2257     }
2258
2259     private void dedupeApnSettings() {
2260         ArrayList<ApnSetting> resultApns = new ArrayList<ApnSetting>();
2261
2262         // coalesce APNs if they are similar enough to prevent
2263         // us from bringing up two data calls with the same interface
2264         int i = 0;
2265         while (i < mAllApnSettings.size() - 1) {
2266             ApnSetting first = mAllApnSettings.get(i);
2267             ApnSetting second = null;
2268             int j = i + 1;
2269             while (j < mAllApnSettings.size()) {
2270                 second = mAllApnSettings.get(j);
2271                 if (apnsSimilar(first, second)) {
2272                     ApnSetting newApn = mergeApns(first, second);
2273                     mAllApnSettings.set(i, newApn);
2274                     first = newApn;
2275                     mAllApnSettings.remove(j);
2276                 } else {
2277                     j++;
2278                 }
2279             }
2280             i++;
2281         }
2282     }
2283
2284     //check whether the types of two APN same (even only one type of each APN is same)
2285     private boolean apnTypeSameAny(ApnSetting first, ApnSetting second) {
2286         if(VDBG) {
2287             StringBuilder apnType1 = new StringBuilder(first.apn + ": ");
2288             for(int index1 = 0; index1 < first.types.length; index1++) {
2289                 apnType1.append(first.types[index1]);
2290                 apnType1.append(",");
2291             }
2292
2293             StringBuilder apnType2 = new StringBuilder(second.apn + ": ");
2294             for(int index1 = 0; index1 < second.types.length; index1++) {
2295                 apnType2.append(second.types[index1]);
2296                 apnType2.append(",");
2297             }
2298             log("APN1: is " + apnType1);
2299             log("APN2: is " + apnType2);
2300         }
2301
2302         for(int index1 = 0; index1 < first.types.length; index1++) {
2303             for(int index2 = 0; index2 < second.types.length; index2++) {
2304                 if(first.types[index1].equals(PhoneConstants.APN_TYPE_ALL) ||
2305                         second.types[index2].equals(PhoneConstants.APN_TYPE_ALL) ||
2306                         first.types[index1].equals(second.types[index2])) {
2307                     if(VDBG)log("apnTypeSameAny: return true");
2308                     return true;
2309                 }
2310             }
2311         }
2312
2313         if(VDBG)log("apnTypeSameAny: return false");
2314         return false;
2315     }
2316
2317     // Check if neither mention DUN and are substantially similar
2318     private boolean apnsSimilar(ApnSetting first, ApnSetting second) {
2319         return (first.canHandleType(PhoneConstants.APN_TYPE_DUN) == false &&
2320                 second.canHandleType(PhoneConstants.APN_TYPE_DUN) == false &&
2321                 Objects.equals(first.apn, second.apn) &&
2322                 !apnTypeSameAny(first, second) &&
2323                 xorEquals(first.proxy, second.proxy) &&
2324                 xorEquals(first.port, second.port) &&
2325                 first.carrierEnabled == second.carrierEnabled &&
2326                 first.bearerBitmask == second.bearerBitmask &&
2327                 first.profileId == second.profileId &&
2328                 Objects.equals(first.mvnoType, second.mvnoType) &&
2329                 Objects.equals(first.mvnoMatchData, second.mvnoMatchData) &&
2330                 xorEquals(first.mmsc, second.mmsc) &&
2331                 xorEquals(first.mmsProxy, second.mmsProxy) &&
2332                 xorEquals(first.mmsPort, second.mmsPort));
2333     }
2334
2335     // equal or one is not specified
2336     private boolean xorEquals(String first, String second) {
2337         return (Objects.equals(first, second) ||
2338                 TextUtils.isEmpty(first) ||
2339                 TextUtils.isEmpty(second));
2340     }
2341
2342     private ApnSetting mergeApns(ApnSetting dest, ApnSetting src) {
2343         ArrayList<String> resultTypes = new ArrayList<String>();
2344         resultTypes.addAll(Arrays.asList(dest.types));
2345         for (String srcType : src.types) {
2346             if (resultTypes.contains(srcType) == false) resultTypes.add(srcType);
2347         }
2348         String mmsc = (TextUtils.isEmpty(dest.mmsc) ? src.mmsc : dest.mmsc);
2349         String mmsProxy = (TextUtils.isEmpty(dest.mmsProxy) ? src.mmsProxy : dest.mmsProxy);
2350         String mmsPort = (TextUtils.isEmpty(dest.mmsPort) ? src.mmsPort : dest.mmsPort);
2351         String proxy = (TextUtils.isEmpty(dest.proxy) ? src.proxy : dest.proxy);
2352         String port = (TextUtils.isEmpty(dest.port) ? src.port : dest.port);
2353         String protocol = src.protocol.equals("IPV4V6") ? src.protocol : dest.protocol;
2354         String roamingProtocol = src.roamingProtocol.equals("IPV4V6") ? src.roamingProtocol :
2355                 dest.roamingProtocol;
2356         int bearerBitmask = (dest.bearerBitmask == 0 || src.bearerBitmask == 0) ?
2357                 0 : (dest.bearerBitmask | src.bearerBitmask);
2358
2359         return new ApnSetting(dest.id, dest.numeric, dest.carrier, dest.apn,
2360                 proxy, port, mmsc, mmsProxy, mmsPort, dest.user, dest.password,
2361                 dest.authType, resultTypes.toArray(new String[0]), protocol,
2362                 roamingProtocol, dest.carrierEnabled, 0, bearerBitmask, dest.profileId,
2363                 (dest.modemCognitive || src.modemCognitive), dest.maxConns, dest.waitTime,
2364                 dest.maxConnsTime, dest.mtu, dest.mvnoType, dest.mvnoMatchData);
2365     }
2366
2367     /** Return the DC AsyncChannel for the new data connection */
2368     private DcAsyncChannel createDataConnection() {
2369         if (DBG) log("createDataConnection E");
2370
2371         int id = mUniqueIdGenerator.getAndIncrement();
2372         DataConnection conn = DataConnection.makeDataConnection(mPhone, id,
2373                                                 this, mDcTesterFailBringUpAll, mDcc);
2374         mDataConnections.put(id, conn);
2375         DcAsyncChannel dcac = new DcAsyncChannel(conn, LOG_TAG);
2376         int status = dcac.fullyConnectSync(mPhone.getContext(), this, conn.getHandler());
2377         if (status == AsyncChannel.STATUS_SUCCESSFUL) {
2378             mDataConnectionAcHashMap.put(dcac.getDataConnectionIdSync(), dcac);
2379         } else {
2380             loge("createDataConnection: Could not connect to dcac=" + dcac + " status=" + status);
2381         }
2382
2383         if (DBG) log("createDataConnection() X id=" + id + " dc=" + conn);
2384         return dcac;
2385     }
2386
2387     private void destroyDataConnections() {
2388         if(mDataConnections != null) {
2389             if (DBG) log("destroyDataConnections: clear mDataConnectionList");
2390             mDataConnections.clear();
2391         } else {
2392             if (DBG) log("destroyDataConnections: mDataConnecitonList is empty, ignore");
2393         }
2394     }
2395
2396     /**
2397      * Build a list of APNs to be used to create PDP's.
2398      *
2399      * @param requestedApnType
2400      * @return waitingApns list to be used to create PDP
2401      *          error when waitingApns.isEmpty()
2402      */
2403     private ArrayList<ApnSetting> buildWaitingApns(String requestedApnType, int radioTech) {
2404         if (DBG) log("buildWaitingApns: E requestedApnType=" + requestedApnType);
2405         ArrayList<ApnSetting> apnList = new ArrayList<ApnSetting>();
2406
2407         if (requestedApnType.equals(PhoneConstants.APN_TYPE_DUN)) {
2408             ApnSetting dun = fetchDunApn();
2409             if (dun != null) {
2410                 apnList.add(dun);
2411                 if (DBG) log("buildWaitingApns: X added APN_TYPE_DUN apnList=" + apnList);
2412                 return apnList;
2413             }
2414         }
2415
2416         IccRecords r = mIccRecords.get();
2417         String operator = (r != null) ? r.getOperatorNumeric() : "";
2418
2419         // This is a workaround for a bug (7305641) where we don't failover to other
2420         // suitable APNs if our preferred APN fails.  On prepaid ATT sims we need to
2421         // failover to a provisioning APN, but once we've used their default data
2422         // connection we are locked to it for life.  This change allows ATT devices
2423         // to say they don't want to use preferred at all.
2424         boolean usePreferred = true;
2425         try {
2426             usePreferred = ! mPhone.getContext().getResources().getBoolean(com.android.
2427                     internal.R.bool.config_dontPreferApn);
2428         } catch (Resources.NotFoundException e) {
2429             if (DBG) log("buildWaitingApns: usePreferred NotFoundException set to true");
2430             usePreferred = true;
2431         }
2432         if (DBG) {
2433             log("buildWaitingApns: usePreferred=" + usePreferred
2434                     + " canSetPreferApn=" + mCanSetPreferApn
2435                     + " mPreferredApn=" + mPreferredApn
2436                     + " operator=" + operator + " radioTech=" + radioTech
2437                     + " IccRecords r=" + r);
2438         }
2439
2440         if (usePreferred && mCanSetPreferApn && mPreferredApn != null &&
2441                 mPreferredApn.canHandleType(requestedApnType)) {
2442             if (DBG) {
2443                 log("buildWaitingApns: Preferred APN:" + operator + ":"
2444                         + mPreferredApn.numeric + ":" + mPreferredApn);
2445             }
2446             if (mPreferredApn.numeric.equals(operator)) {
2447                 if (ServiceState.bitmaskHasTech(mPreferredApn.bearerBitmask, radioTech)) {
2448                     apnList.add(mPreferredApn);
2449                     if (DBG) log("buildWaitingApns: X added preferred apnList=" + apnList);
2450                     return apnList;
2451                 } else {
2452                     if (DBG) log("buildWaitingApns: no preferred APN");
2453                     setPreferredApn(-1);
2454                     mPreferredApn = null;
2455                 }
2456             } else {
2457                 if (DBG) log("buildWaitingApns: no preferred APN");
2458                 setPreferredApn(-1);
2459                 mPreferredApn = null;
2460             }
2461         }
2462         if (mAllApnSettings != null) {
2463             if (DBG) log("buildWaitingApns: mAllApnSettings=" + mAllApnSettings);
2464             for (ApnSetting apn : mAllApnSettings) {
2465                 if (apn.canHandleType(requestedApnType)) {
2466                     if (ServiceState.bitmaskHasTech(apn.bearerBitmask, radioTech)) {
2467                         if (DBG) log("buildWaitingApns: adding apn=" + apn);
2468                         apnList.add(apn);
2469                     } else {
2470                         if (DBG) {
2471                             log("buildWaitingApns: bearerBitmask:" + apn.bearerBitmask + " does " +
2472                                     "not include radioTech:" + radioTech);
2473                         }
2474                     }
2475                 } else if (DBG) {
2476                     log("buildWaitingApns: couldn't handle requesedApnType="
2477                             + requestedApnType);
2478                 }
2479             }
2480         } else {
2481             loge("mAllApnSettings is empty!");
2482         }
2483         if (DBG) log("buildWaitingApns: X apnList=" + apnList);
2484         return apnList;
2485     }
2486
2487     private String apnListToString (ArrayList<ApnSetting> apns) {
2488         StringBuilder result = new StringBuilder();
2489         for (int i = 0, size = apns.size(); i < size; i++) {
2490             result.append('[')
2491                   .append(apns.get(i).toString())
2492                   .append(']');
2493         }
2494         return result.toString();
2495     }
2496
2497     private void setPreferredApn(int pos) {
2498         if (!mCanSetPreferApn) {
2499             log("setPreferredApn: X !canSEtPreferApn");
2500             return;
2501         }
2502
2503         String subId = Long.toString(mPhone.getSubId());
2504         Uri uri = Uri.withAppendedPath(PREFERAPN_NO_UPDATE_URI_USING_SUBID, subId);
2505         log("setPreferredApn: delete");
2506         ContentResolver resolver = mPhone.getContext().getContentResolver();
2507         resolver.delete(uri, null, null);
2508
2509         if (pos >= 0) {
2510             log("setPreferredApn: insert");
2511             ContentValues values = new ContentValues();
2512             values.put(APN_ID, pos);
2513             resolver.insert(uri, values);
2514         }
2515     }
2516
2517     private ApnSetting getPreferredApn() {
2518         if (mAllApnSettings.isEmpty()) {
2519             log("getPreferredApn: X not found mAllApnSettings.isEmpty");
2520             return null;
2521         }
2522
2523         String subId = Long.toString(mPhone.getSubId());
2524         Uri uri = Uri.withAppendedPath(PREFERAPN_NO_UPDATE_URI_USING_SUBID, subId);
2525         Cursor cursor = mPhone.getContext().getContentResolver().query(
2526                 uri, new String[] { "_id", "name", "apn" },
2527                 null, null, Telephony.Carriers.DEFAULT_SORT_ORDER);
2528
2529         if (cursor != null) {
2530             mCanSetPreferApn = true;
2531         } else {
2532             mCanSetPreferApn = false;
2533         }
2534         log("getPreferredApn: mRequestedApnType=" + mRequestedApnType + " cursor=" + cursor
2535                 + " cursor.count=" + ((cursor != null) ? cursor.getCount() : 0));
2536
2537         if (mCanSetPreferApn && cursor.getCount() > 0) {
2538             int pos;
2539             cursor.moveToFirst();
2540             pos = cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers._ID));
2541             for(ApnSetting p : mAllApnSettings) {
2542                 log("getPreferredApn: apnSetting=" + p);
2543                 if (p.id == pos && p.canHandleType(mRequestedApnType)) {
2544                     log("getPreferredApn: X found apnSetting" + p);
2545                     cursor.close();
2546                     return p;
2547                 }
2548             }
2549         }
2550
2551         if (cursor != null) {
2552             cursor.close();
2553         }
2554
2555         log("getPreferredApn: X not found");
2556         return null;
2557     }
2558
2559     @Override
2560     public void handleMessage (Message msg) {
2561         if (DBG) log("handleMessage msg=" + msg);
2562
2563         if (!mPhone.mIsTheCurrentActivePhone || mIsDisposed) {
2564             loge("handleMessage: Ignore GSM msgs since GSM phone is inactive");
2565             return;
2566         }
2567
2568         switch (msg.what) {
2569             case DctConstants.EVENT_RECORDS_LOADED:
2570                 onRecordsLoaded();
2571                 break;
2572
2573             case DctConstants.EVENT_DATA_CONNECTION_DETACHED:
2574                 onDataConnectionDetached();
2575                 break;
2576
2577             case DctConstants.EVENT_DATA_CONNECTION_ATTACHED:
2578                 onDataConnectionAttached();
2579                 break;
2580
2581             case DctConstants.EVENT_DO_RECOVERY:
2582                 doRecovery();
2583                 break;
2584
2585             case DctConstants.EVENT_APN_CHANGED:
2586                 onApnChanged();
2587                 break;
2588
2589             case DctConstants.EVENT_PS_RESTRICT_ENABLED:
2590                 /**
2591                  * We don't need to explicitly to tear down the PDP context
2592                  * when PS restricted is enabled. The base band will deactive
2593                  * PDP context and notify us with PDP_CONTEXT_CHANGED.
2594                  * But we should stop the network polling and prevent reset PDP.
2595                  */
2596                 if (DBG) log("EVENT_PS_RESTRICT_ENABLED " + mIsPsRestricted);
2597                 stopNetStatPoll();
2598                 stopDataStallAlarm();
2599                 mIsPsRestricted = true;
2600                 break;
2601
2602             case DctConstants.EVENT_PS_RESTRICT_DISABLED:
2603                 /**
2604                  * When PS restrict is removed, we need setup PDP connection if
2605                  * PDP connection is down.
2606                  */
2607                 if (DBG) log("EVENT_PS_RESTRICT_DISABLED " + mIsPsRestricted);
2608                 mIsPsRestricted  = false;
2609                 if (isConnected()) {
2610                     startNetStatPoll();
2611                     startDataStallAlarm(DATA_STALL_NOT_SUSPECTED);
2612                 } else {
2613                     // TODO: Should all PDN states be checked to fail?
2614                     if (mState == DctConstants.State.FAILED) {
2615                         cleanUpAllConnections(false, Phone.REASON_PS_RESTRICT_ENABLED);
2616                         mReregisterOnReconnectFailure = false;
2617                     }
2618                     ApnContext apnContext = mApnContexts.get(PhoneConstants.APN_TYPE_DEFAULT);
2619                     if (apnContext != null) {
2620                         apnContext.setReason(Phone.REASON_PS_RESTRICT_ENABLED);
2621                         trySetupData(apnContext);
2622                     } else {
2623                         loge("**** Default ApnContext not found ****");
2624                         if (Build.IS_DEBUGGABLE) {
2625                             throw new RuntimeException("Default ApnContext not found");
2626                         }
2627                     }
2628                 }
2629                 break;
2630
2631             case DctConstants.EVENT_TRY_SETUP_DATA:
2632                 if (msg.obj instanceof ApnContext) {
2633                     onTrySetupData((ApnContext)msg.obj);
2634                 } else if (msg.obj instanceof String) {
2635                     onTrySetupData((String)msg.obj);
2636                 } else {
2637                     loge("EVENT_TRY_SETUP request w/o apnContext or String");
2638                 }
2639                 break;
2640
2641             case DctConstants.EVENT_CLEAN_UP_CONNECTION:
2642                 boolean tearDown = (msg.arg1 == 0) ? false : true;
2643                 if (DBG) log("EVENT_CLEAN_UP_CONNECTION tearDown=" + tearDown);
2644                 if (msg.obj instanceof ApnContext) {
2645                     cleanUpConnection(tearDown, (ApnContext)msg.obj);
2646                 } else {
2647                     loge("EVENT_CLEAN_UP_CONNECTION request w/o apn context, call super");
2648                     super.handleMessage(msg);
2649                 }
2650                 break;
2651             case DctConstants.EVENT_SET_INTERNAL_DATA_ENABLE:
2652                 boolean enabled = (msg.arg1 == DctConstants.ENABLED) ? true : false;
2653                 onSetInternalDataEnabled(enabled, (Message) msg.obj);
2654                 break;
2655
2656             case DctConstants.EVENT_CLEAN_UP_ALL_CONNECTIONS:
2657                 Message mCause = obtainMessage(DctConstants.EVENT_CLEAN_UP_ALL_CONNECTIONS, null);
2658                 if ((msg.obj != null) && (msg.obj instanceof String)) {
2659                     mCause.obj = msg.obj;
2660                 }
2661                 super.handleMessage(mCause);
2662                 break;
2663
2664             case DctConstants.EVENT_DATA_RAT_CHANGED:
2665                 //May new Network allow setupData, so try it here
2666                 setupDataOnConnectableApns(Phone.REASON_NW_TYPE_CHANGED,
2667                         RetryFailures.ONLY_ON_CHANGE);
2668                 break;
2669
2670             case DctConstants.CMD_CLEAR_PROVISIONING_SPINNER:
2671                 // Check message sender intended to clear the current spinner.
2672                 if (mProvisioningSpinner == msg.obj) {
2673                     mProvisioningSpinner.dismiss();
2674                     mProvisioningSpinner = null;
2675                 }
2676                 break;
2677
2678             default:
2679                 // handle the message in the super class DataConnectionTracker
2680                 super.handleMessage(msg);
2681                 break;
2682         }
2683     }
2684
2685     protected int getApnProfileID(String apnType) {
2686         if (TextUtils.equals(apnType, PhoneConstants.APN_TYPE_IMS)) {
2687             return RILConstants.DATA_PROFILE_IMS;
2688         } else if (TextUtils.equals(apnType, PhoneConstants.APN_TYPE_FOTA)) {
2689             return RILConstants.DATA_PROFILE_FOTA;
2690         } else if (TextUtils.equals(apnType, PhoneConstants.APN_TYPE_CBS)) {
2691             return RILConstants.DATA_PROFILE_CBS;
2692         } else if (TextUtils.equals(apnType, PhoneConstants.APN_TYPE_IA)) {
2693             return RILConstants.DATA_PROFILE_DEFAULT; // DEFAULT for now
2694         } else if (TextUtils.equals(apnType, PhoneConstants.APN_TYPE_DUN)) {
2695             return RILConstants.DATA_PROFILE_TETHERED;
2696         } else {
2697             return RILConstants.DATA_PROFILE_DEFAULT;
2698         }
2699     }
2700
2701     private int getCellLocationId() {
2702         int cid = -1;
2703         CellLocation loc = mPhone.getCellLocation();
2704
2705         if (loc != null) {
2706             if (loc instanceof GsmCellLocation) {
2707                 cid = ((GsmCellLocation)loc).getCid();
2708             } else if (loc instanceof CdmaCellLocation) {
2709                 cid = ((CdmaCellLocation)loc).getBaseStationId();
2710             }
2711         }
2712         return cid;
2713     }
2714
2715     private IccRecords getUiccRecords(int appFamily) {
2716         return mUiccController.getIccRecords(mPhone.getPhoneId(), appFamily);
2717     }
2718
2719
2720     @Override
2721     protected void onUpdateIcc() {
2722         if (mUiccController == null ) {
2723             return;
2724         }
2725
2726         IccRecords newIccRecords = getUiccRecords(UiccController.APP_FAM_3GPP);
2727
2728         IccRecords r = mIccRecords.get();
2729         if (r != newIccRecords) {
2730             if (r != null) {
2731                 log("Removing stale icc objects.");
2732                 r.unregisterForRecordsLoaded(this);
2733                 mIccRecords.set(null);
2734             }
2735             if (newIccRecords != null) {
2736                 log("New records found");
2737                 mIccRecords.set(newIccRecords);
2738                 newIccRecords.registerForRecordsLoaded(
2739                         this, DctConstants.EVENT_RECORDS_LOADED, null);
2740             } else {
2741                 onSimNotReady();
2742             }
2743         }
2744     }
2745
2746     public void update() {
2747         log("update sub = " + mPhone.getSubId());
2748         log("update(): Active DDS, register for all events now!");
2749         registerForAllEvents();
2750         onUpdateIcc();
2751
2752         mUserDataEnabled = getDataEnabled();
2753
2754         if (mPhone instanceof CDMALTEPhone) {
2755             ((CDMALTEPhone)mPhone).updateCurrentCarrierInProvider();
2756         } else if (mPhone instanceof GSMPhone) {
2757             ((GSMPhone)mPhone).updateCurrentCarrierInProvider();
2758         } else {
2759             log("Phone object is not MultiSim. This should not hit!!!!");
2760         }
2761     }
2762
2763     @Override
2764     public void cleanUpAllConnections(String cause) {
2765         cleanUpAllConnections(cause, null);
2766     }
2767
2768     public void updateRecords() {
2769         onUpdateIcc();
2770     }
2771
2772     public void cleanUpAllConnections(String cause, Message disconnectAllCompleteMsg) {
2773         log("cleanUpAllConnections");
2774         if (disconnectAllCompleteMsg != null) {
2775             mDisconnectAllCompleteMsgList.add(disconnectAllCompleteMsg);
2776         }
2777
2778         Message msg = obtainMessage(DctConstants.EVENT_CLEAN_UP_ALL_CONNECTIONS);
2779         msg.obj = cause;
2780         sendMessage(msg);
2781     }
2782
2783     protected void notifyDataDisconnectComplete() {
2784         log("notifyDataDisconnectComplete");
2785         for (Message m: mDisconnectAllCompleteMsgList) {
2786             m.sendToTarget();
2787         }
2788         mDisconnectAllCompleteMsgList.clear();
2789     }
2790
2791
2792     protected void notifyAllDataDisconnected() {
2793         sEnableFailFastRefCounter = 0;
2794         mFailFast = false;
2795         mAllDataDisconnectedRegistrants.notifyRegistrants();
2796     }
2797
2798     public void registerForAllDataDisconnected(Handler h, int what, Object obj) {
2799         mAllDataDisconnectedRegistrants.addUnique(h, what, obj);
2800
2801         if (isDisconnected()) {
2802             log("notify All Data Disconnected");
2803             notifyAllDataDisconnected();
2804         }
2805     }
2806
2807     public void unregisterForAllDataDisconnected(Handler h) {
2808         mAllDataDisconnectedRegistrants.remove(h);
2809     }
2810
2811
2812     @Override
2813     protected void onSetInternalDataEnabled(boolean enable) {
2814         if (DBG) log("onSetInternalDataEnabled: enabled=" + enable);
2815         onSetInternalDataEnabled(enable, null);
2816     }
2817
2818     protected void onSetInternalDataEnabled(boolean enabled, Message onCompleteMsg) {
2819         if (DBG) log("onSetInternalDataEnabled: enabled=" + enabled);
2820         boolean sendOnComplete = true;
2821
2822         synchronized (mDataEnabledLock) {
2823             mInternalDataEnabled = enabled;
2824             if (enabled) {
2825                 log("onSetInternalDataEnabled: changed to enabled, try to setup data call");
2826                 onTrySetupData(Phone.REASON_DATA_ENABLED);
2827             } else {
2828                 sendOnComplete = false;
2829                 log("onSetInternalDataEnabled: changed to disabled, cleanUpAllConnections");
2830                 cleanUpAllConnections(null, onCompleteMsg);
2831             }
2832         }
2833
2834         if (sendOnComplete) {
2835             if (onCompleteMsg != null) {
2836                 onCompleteMsg.sendToTarget();
2837             }
2838         }
2839     }
2840
2841     public boolean setInternalDataEnabledFlag(boolean enable) {
2842         if (DBG) log("setInternalDataEnabledFlag(" + enable + ")");
2843
2844         if (mInternalDataEnabled != enable) {
2845             mInternalDataEnabled = enable;
2846         }
2847         return true;
2848     }
2849
2850     @Override
2851     public boolean setInternalDataEnabled(boolean enable) {
2852         return setInternalDataEnabled(enable, null);
2853     }
2854
2855     public boolean setInternalDataEnabled(boolean enable, Message onCompleteMsg) {
2856         if (DBG) log("setInternalDataEnabled(" + enable + ")");
2857
2858         Message msg = obtainMessage(DctConstants.EVENT_SET_INTERNAL_DATA_ENABLE, onCompleteMsg);
2859         msg.arg1 = (enable ? DctConstants.ENABLED : DctConstants.DISABLED);
2860         sendMessage(msg);
2861         return true;
2862     }
2863
2864     public void setDataAllowed(boolean enable, Message response) {
2865          if (DBG) log("setDataAllowed: enable=" + enable);
2866          mIsCleanupRequired = !enable;
2867          mPhone.mCi.setDataAllowed(enable, response);
2868          mInternalDataEnabled = enable;
2869     }
2870
2871     @Override
2872     protected void log(String s) {
2873         Rlog.d(LOG_TAG, "[" + mPhone.getPhoneId() + "]" + s);
2874     }
2875
2876     @Override
2877     protected void loge(String s) {
2878         Rlog.e(LOG_TAG, "[" + mPhone.getPhoneId() + "]" + s);
2879     }
2880
2881     @Override
2882     public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2883         pw.println("DcTracker extends:");
2884         super.dump(fd, pw, args);
2885         pw.println(" mReregisterOnReconnectFailure=" + mReregisterOnReconnectFailure);
2886         pw.println(" canSetPreferApn=" + mCanSetPreferApn);
2887         pw.println(" mApnObserver=" + mApnObserver);
2888         pw.println(" getOverallState=" + getOverallState());
2889         pw.println(" mDataConnectionAsyncChannels=%s\n" + mDataConnectionAcHashMap);
2890         pw.println(" mAttached=" + mAttached.get());
2891     }
2892
2893     @Override
2894     public String[] getPcscfAddress(String apnType) {
2895         log("getPcscfAddress()");
2896         ApnContext apnContext = null;
2897
2898         if(apnType == null){
2899             log("apnType is null, return null");
2900             return null;
2901         }
2902
2903         if (TextUtils.equals(apnType, PhoneConstants.APN_TYPE_EMERGENCY)) {
2904             apnContext = mApnContexts.get(PhoneConstants.APN_TYPE_EMERGENCY);
2905         } else if (TextUtils.equals(apnType, PhoneConstants.APN_TYPE_IMS)) {
2906             apnContext = mApnContexts.get(PhoneConstants.APN_TYPE_IMS);
2907         } else {
2908             log("apnType is invalid, return null");
2909             return null;
2910         }
2911
2912         if (apnContext == null) {
2913             log("apnContext is null, return null");
2914             return null;
2915         }
2916
2917         DcAsyncChannel dcac = apnContext.getDcAc();
2918         String[] result = null;
2919
2920         if (dcac != null) {
2921             result = dcac.getPcscfAddr();
2922
2923             for (int i = 0; i < result.length; i++) {
2924                 log("Pcscf[" + i + "]: " + result[i]);
2925             }
2926             return result;
2927         }
2928         return null;
2929     }
2930
2931     @Override
2932     public void setImsRegistrationState(boolean registered) {
2933         log("setImsRegistrationState - mImsRegistrationState(before): "+ mImsRegistrationState
2934                 + ", registered(current) : " + registered);
2935
2936         if (mPhone == null) return;
2937
2938         ServiceStateTracker sst = mPhone.getServiceStateTracker();
2939         if (sst == null) return;
2940
2941         sst.setImsRegistrationState(registered);
2942     }
2943
2944     /**
2945      * Read APN configuration from Telephony.db for Emergency APN
2946      * All opertors recognize the connection request for EPDN based on APN type
2947      * PLMN name,APN name are not mandatory parameters
2948      */
2949     private void initEmergencyApnSetting() {
2950         // Operator Numeric is not available when sim records are not loaded.
2951         // Query Telephony.db with APN type as EPDN request does not
2952         // require APN name, plmn and all operators support same APN config.
2953         // DB will contain only one entry for Emergency APN
2954         String selection = "type=\"emergency\"";
2955         Cursor cursor = mPhone.getContext().getContentResolver().query(
2956                 Telephony.Carriers.CONTENT_URI, null, selection, null, null);
2957
2958         if (cursor != null) {
2959             if (cursor.getCount() > 0) {
2960                 if (cursor.moveToFirst()) {
2961                     mEmergencyApn = makeApnSetting(cursor);
2962                 }
2963             }
2964             cursor.close();
2965         }
2966     }
2967
2968     /**
2969      * Add the Emergency APN settings to APN settings list
2970      */
2971     private void addEmergencyApnSetting() {
2972         if(mEmergencyApn != null) {
2973             if(mAllApnSettings == null) {
2974                 mAllApnSettings = new ArrayList<ApnSetting>();
2975             } else {
2976                 boolean hasEmergencyApn = false;
2977                 for (ApnSetting apn : mAllApnSettings) {
2978                     if (ArrayUtils.contains(apn.types, PhoneConstants.APN_TYPE_EMERGENCY)) {
2979                         hasEmergencyApn = true;
2980                         break;
2981                     }
2982                 }
2983
2984                 if(hasEmergencyApn == false) {
2985                     mAllApnSettings.add(mEmergencyApn);
2986                 } else {
2987                     log("addEmergencyApnSetting - E-APN setting is already present");
2988                 }
2989             }
2990         }
2991     }
2992
2993     private void cleanUpConnectionsOnUpdatedApns(boolean tearDown) {
2994         if (DBG) log("cleanUpConnectionsOnUpdatedApns: tearDown=" + tearDown);
2995         if (mAllApnSettings.isEmpty()) {
2996             cleanUpAllConnections(tearDown, Phone.REASON_APN_CHANGED);
2997         } else {
2998             for (ApnContext apnContext : mApnContexts.values()) {
2999                 if (VDBG) log("cleanUpConnectionsOnUpdatedApns for "+ apnContext);
3000
3001                 boolean cleanUpApn = true;
3002                 ArrayList<ApnSetting> currentWaitingApns = apnContext.getWaitingApns();
3003
3004                 if ((currentWaitingApns != null) && (!apnContext.isDisconnected())) {
3005                     int radioTech = mPhone.getServiceState().getRilDataRadioTechnology();
3006                     ArrayList<ApnSetting> waitingApns = buildWaitingApns(
3007                             apnContext.getApnType(), radioTech);
3008                     if (VDBG) log("new waitingApns:" + waitingApns);
3009                     if (waitingApns.size() == currentWaitingApns.size()) {
3010                         cleanUpApn = false;
3011                         for (int i = 0; i < waitingApns.size(); i++) {
3012                             if (!currentWaitingApns.get(i).equals(waitingApns.get(i))) {
3013                                 if (VDBG) log("new waiting apn is different at " + i);
3014                                 cleanUpApn = true;
3015                                 apnContext.setWaitingApns(waitingApns);
3016                                 break;
3017                             }
3018                         }
3019                     }
3020                 }
3021
3022                 if (cleanUpApn) {
3023                     apnContext.setReason(Phone.REASON_APN_CHANGED);
3024                     cleanUpConnection(true, apnContext);
3025                 }
3026             }
3027         }
3028
3029         if (!isConnected()) {
3030             stopNetStatPoll();
3031             stopDataStallAlarm();
3032         }
3033
3034         mRequestedApnType = PhoneConstants.APN_TYPE_DEFAULT;
3035
3036         if (DBG) log("mDisconnectPendingCount = " + mDisconnectPendingCount);
3037         if (tearDown && mDisconnectPendingCount == 0) {
3038             notifyDataDisconnectComplete();
3039             notifyAllDataDisconnected();
3040         }
3041     }
3042 }